亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在某些情況下無法打印正確的結果

在某些情況下無法打印正確的結果

牛魔王的故事 2023-04-26 10:48:38
我創建了一個 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. 如果沒有重復,程序打印“無重復” 該程序正常工作......除了它打印“無重復”即使有重復。我嘗試了很多事情,例如使用布爾標志(如果找到重復項,則為真,然后打印結果),還將其設置為假,插入更多 if 條件,將“無重復項” print.out 放在大括號內的不同位置,但沒有任何效果。如果我將“無重復項” print.out 放在循環之外,那么即使有重復項它也會打印。如果我將“無重復項” 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.print("Please enter your array values: ");for (i = 0; i < arraySize; i++) {    arrayList[i] = sc.nextInt();}boolean duplicates = false;for (i = 0; i < arrayList.length - 1; i++) {    for (j = i + 1; j < arrayList.length; j++) {        if (arrayList[i] == arrayList[j]) {            System.out.println("Duplicate number: " + arrayList[i]);            System.out.println("Duplicate number's index: " + j);            break;        }    }}
查看完整描述

1 回答

?
慕婉清6462132

TA貢獻1804條經驗 獲得超2個贊

您有一個duplicates標志,您將其初始化為,但在有重復項時false從不設置為。假設你在循環之后true有一個簡單的(如果你不需要的話),它應該看起來像iffor


boolean duplicates = false;

for (i = 0; i < arrayList.length - 1; i++) {

    for (j = i + 1; j < arrayList.length; j++) {

        if (arrayList[i] == arrayList[j]) {

            duplicates = true; // <-- Add this.

            System.out.println("Duplicate number: " + arrayList[i]);

            System.out.println("Duplicate number's index: " + j);

            break;

        }

    }

}

if (!duplicates) {

    System.out.println("no duplicates");

}


查看完整回答
反對 回復 2023-04-26
  • 1 回答
  • 0 關注
  • 141 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號