我創建了一個 Java 程序,它將用戶輸入作為一個整數數組,并打印該數組中的任何重復值及其索引。例如,用戶輸入 5 作為數組大小,然后輸入 5 個數字,例如 1、1、1、1 和 1。程序應打?。?Duplicate number: 1 Duplicate number's index: 1 Duplicate number: 1 Duplicate number's index : 2 重復數:1 重復數索引:3 重復數:1 重復數索引:4但是,程序打?。?重復數字:1 重復數字索引:1 重復數字:1 重復數字索引:2 重復數字:1 重復數字索引:3 重復數字:1 重復數字索引:4 重復數字:1 重復數字索引:2重復數:1 重復數索引:3 重復數:1 重復數索引:4 重復數:1 重復數索引:3 重復數:1 重復數索引:4 重復數:1 重復數索引:4我嘗試調試程序,得到的結論是,因為打印結果是在循環內的,只要循環運行并滿足一定的條件,就會有多次打印。但是,我找不到使代碼不同的方法,因此只打印正確數量的結果。我試圖調整代碼:插入 break 和 continue,將 print.out 語句放在循環之外,但沒有任何效果。 Scanner sc = new Scanner(System.in); int i, j; System.out.println("This program lets you enter an array of numbers, and then tells you if any of the numbers are duplices, and what the duplicates' indices are. \nPlease enter your desired array size: "); int arraySize = sc.nextInt(); while (arraySize <= 0) { System.out.println(arraySize + " is not a valid number. \nPlease enter your desired array size: "); arraySize = sc.nextInt(); continue;} int[] arrayList = new int[arraySize]; System.out.println("Please enter your array values: "); for (i = 0; i < arraySize; i++) { arrayList[i] = sc.nextInt(); } for (i = 0; i < arrayList.length; i++) { for (j = i + 1; j < arrayList.length; j++) { if (i!=j && arrayList[i] == arrayList[j]) { System.out.println("Duplicate number: " + arrayList[i]); System.out.println("Duplicate number's index: " + j); } else if (i!=j && arrayList[i] != arrayList[j]) {System.out.println("There are no duplicates"); } } }
1 回答

眼眸繁星
TA貢獻1873條經驗 獲得超9個贊
您正在做的是找到重復項的重復項。取 1,1,1。首先,您在索引 1 和 2 處找到 1、索引 0 的兩個副本。然后您在索引 2 處找到 1、索引 1 的副本。有多種解決方案。
跟蹤遇到的重復項。如果一個已經被外循環處理過,就不要再處理了。您可以通過單獨放置
list
找到的重復項并使用該contains
方法檢查它是否存在來做到這一點。對列表進行排序,然后查找重復序列。這改變了位置,所以它可能不是你想要的。
找到重復項后將其刪除。這也會改變位置,因此它可能也不是您想要的。我還增加了一些額外的復雜性。
你也有不同的問題。
當遇到重復項時,您還會打印出沒有找到重復項,這看起來很矛盾。要解決此問題,請使用標志
boolean
并在找到重復項時將其設置為 false,并在退出循環時使用它來打印消息。因為你開始你的內部循環比外部循環多一個(即
j = 0 and i = j+1
)它們永遠不會相同。所以你不需要測試(i!=j)
。此外,外循環的終止應該是arrayList.length-1
.
添加回答
舉報
0/150
提交
取消