2016-12-03 18 views
1

我在做一個小程序,並且遇到了問題。如果循環中的數據與第一個循環中的數據不同,則Java輸出

事情是我想確認(在這種情況下循環通過2次)輸入的數據是相同的兩次。如果它是錯誤的,它應該在最後輸出它不正確。

 int yearInput; 
    int monthInput; 
    int i = 2; 
    int x = 1; 
    int inputvalid; 
    int same = 0; 


    while (x == 1) { 
     while (i >= 1) { 
     System.out.println(i); 
     i--; 
     System.out.println("enter year"); 
     yearInput = kb.nextInt(); 
     System.out.println("enter month"); 
     monthInput = kb.nextInt(); 
     } 

     x--; 
    } 

    same = ???; 

    if(same==0){ 
    System.out.print("Both loop inputs are same"); 
    } 
    else{ 
    System.out.println("Both loop inputs are not same"); 
    } 

    } 

雖然這個計劃只是爲了說明問題,x和i的值是在真正的程序變量,我只是無法通過該段去。

+0

我想添加一個計數器以某種方式附加到輸入? –

+0

您可以將數據保存在某處在一個數組中。 – SpiderPig

+0

爲什麼要用while循環代替if語句?現在你只有兩個無限循環,因爲'x'和'i'永遠不會改變。 –

回答

0

您首先使用了兩個數組,它們會導致一個嵌套循環,這很可能是您不想要的東西。如果你想檢查兩個循環的結果,你可以用用戶輸入創建一個循環,然後將其存儲在變量中,如loopOneResult。在第二個循環中,您可以執行相同的操作,然後在兩個循環之外使用equals或equalsIgnoreCase方法比較結果。這肯定會告訴你,如果循環是相同的。如果這有助於批准這個答案:)

+0

但如果有100個循環呢?唯一的方法是使用數組嗎? –

+0

確實。您無法按照您使用的方式使用循環,因爲它會輪流嵌套循環,使您很難使用 – Aaron

+0

謝謝!然後我會嘗試學習數組! –

相關問題