2012-04-01 39 views
1

爲這些準則:
這個循環中的邏輯錯誤是什麼?

編寫一個循環,從標準輸入中讀取正整數,並在讀取非正整數時終止。循環終止後,它會打印出來,並由一個空格和一行分開,讀取所有偶數整數的總和以及所有奇數整數的總和。聲明任何需要的變量。

假定變量stdin的可用性引用與標準輸入關聯的Scanner對象。

我寫了這段代碼,但它的硬件軟件不會除了它由於邏輯錯誤。我似乎無法找到這裏的邏輯錯誤。有人能指出它有什麼問題嗎?

int sumP=0; 
    int sumO=0; 
    Scanner stdin = new Scanner (System.in); 

    System.out.println("enter an odd or even number"); 

    while (stdin.nextInt() >= 0){ 
    if(stdin.nextInt()%2 == 0) 
     sumP+= stdin.nextInt(); 
    else 
     sumO += stdin.nextInt(); 
    } 
    System.out.println(sumP + " " + sumO); 

回答

7

您需要保存您讀取的值,否則您將在while循環和添加中使用不同的值。

int n; 
while((n = stdin.readInt()) >= 0) { 
    // use the same value of n 
+0

找到謝謝你的幫助。 並感謝您的解釋。 – gnawthatthingoffyourface 2012-04-01 20:09:50

+2

有時當你調用同樣的方法時,你會得到同樣的結果,但是對於流,你只需要獲得下一個值。 – 2012-04-01 20:23:53

0

這個工作對myprogramminglab - Java的

int sum=0; 
boolean areMore = true; 
int negative; 
while (areMore) 
{ 
    int number = stdin.nextInt(); 
    if (number <= 0) 
    areMore = false; 
    else if (number %2 ==0) 
    sum = sum + number;  
else 
    negative = sum + number; 
}  
System.out.println(sum); 
0
int number = 1; 
while (stdin.hasNextInt() && number > 0) 
{ 
      number = stdin.nextInt(); 
      if (number % 2 == 0 && number > 0) 
         System.out.print(number + " "); 
} 

這個問題的答案和許多其他代碼實驗室練習,可以在Java Codelab Solutions