簡體   English   中英

For 循環打印出乎意​​料的次數

[英]For loop printing an unexpected number of times

public static void main (String[] args) {
    Scanner input = new Scanner(System.in);
    int[] array = new int[5];
    System.out.print("Please enter five numbers. \na=");
    array[0] = input.nextInt();
    System.out.print("\nb=");
    array[1] = input.nextInt();
    System.out.print("\nc=");
    array[2] = input.nextInt();
    System.out.print("\nd=");
    array[3] = input.nextInt();
    System.out.print("\ne=");
    array[4] = input.nextInt();
    boolean totalIsZero = false;
    for (int i=0;i<array.length ;i++) {
        for (int j=1;i>j ;j++ ) {       
            if ((array[i] + array[j])==0) {
                System.out.println("The numbers " + array[i] + " and " + array[j] + " have a total sum equal to 0.");
                totalIsZero = true;
            }
        }
    }
    if (!totalIsZero) {
        System.out.print("None of the numbers have a total sum of 0 with each other. ");
    }
}

這是我剛剛編寫的一些簡單代碼。 它的任務是檢查數組(由五個數字組成)中每兩個數字之間的和是否等於零。

我遇到的問題是,當有兩對數字都等於 0 時,在程序結束時,只有一對數字的消息,而不是兩個數字,正如我預期的那樣。

我該如何解決這個問題,以便用戶可以讀到有兩對等於 0 的數字?

不確定這是否會完美運行,因為我還沒有測試過它,也有一段時間沒有使用過 java,但只需按照您在帖子中的方式創建數組,但請嘗試其余的實際大部分功能。

// various input calls above^ to create array
int count = 0;
for(int i = 0; i < array.length; i++)
{
    for(int j = i + 1; j < array.length; j++)
    {
        if(array[i] + array[j] == 0)
        {
            System.out.println("The numbers " + array[i] + " and " +
                               array[j] + 
                               " have a sum equal to zero.");
            count++;
        }
     }
}

if(count == 0)
{
    System.out.println("No sum between any numbers is equal to 0");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM