2015-10-05 74 views
0

我有這樣的代碼:爲什麼我的代碼不能運行?

import java.util.Scanner; 

public class PositiveNegative { public static void main(String[] args) { 
     int numbers, plus = 0, minus = 0; 
     int count = 0; 
     double total = 0; 

     Scanner scan = new Scanner(System.in); 
     System.out.print("Enter an integer (0 to quit): "); 
     numbers = scan.nextInt(); 

     while(numbers != 0) 
     { 
     total += numbers; 
     if(numbers > 0) 
      plus++; 
     if(numbers < 0) 
      minus++; 
     } 
     System.out.println("The number of positives is: " +plus); 
     System.out.println("The number of negatives is: " +minus); 
     System.out.println("The number of total is: " +total);  
    } 
} 

的問題是,我嘗試運行它,並鍵入數字,但它什麼都不做。我需要它,這樣當你鍵入0時,它停止接收數字並開始處理代碼。我該怎麼辦?

+2

你永遠不修改'numbers',所以一旦它進入循環,它永遠不會離開 – MadProgrammer

+0

如果你輸入的數字不是0,那麼你被困在一個**無盡**循環中。只需在運行程序時檢查CPU使用情況......您還需要在循環中有'numbers = scan.nextInt()'。 – bmk

回答

0

試試這個:

import java.util.Scanner; 

public class PositiveNegative { 
    public static void main(String[] args) { 
     int numbers = 0, plus = 0, minus = 0; 
     double total = 0; 
     do{ 
      Scanner scan = new Scanner(System.in); 
      System.out.print("Enter an integer (0 to quit): "); 
      numbers = Integer.valueOf(scan.nextLine()); 
      total += numbers; 
      if (numbers > 0) 
       plus++; 
      if (numbers < 0) 
       minus++; 
     } 
     while (numbers != 0); 
     System.out.println("The number of positives is: " + plus); 
     System.out.println("The number of negatives is: " + minus); 
     System.out.println("The number of total is: " + total); 
    } 
} 

把你的掃描儀在while循環,使每次循環開始它會要求用戶輸入。

+0

爲什麼數字被初始化爲-1?只是爲了確保while循環第一次運行? –

+0

他是對的,在這種情況下你使用do while循環。 – Jannik

0

您需要更新numbers或者您的循環將永遠運行。我建議使用大括號(和else)。類似的,

System.out.print("Enter an integer (0 to quit): "); 
numbers = scan.nextInt(); 
while (numbers != 0) { 
    total += numbers; 
    if (numbers > 0) { 
     plus++; 
    } else if (numbers < 0) { 
     minus++; 
    } 
    System.out.print("Enter an integer (0 to quit): "); 
    numbers = scan.nextInt(); 
} 

或者,您可以使用do-while循環。然後你只需要一個提示副本。像,

do { 
    System.out.print("Enter an integer (0 to quit): "); 
    numbers = scan.nextInt(); 
    total += numbers; 
    if (numbers > 0) { 
     plus++; 
    } else if (numbers < 0) { 
     minus++; 
    } 
} while (numbers != 0); 
0

您必須每次修改numbers才能使其在您的while中工作。

因此,在現有的代碼,只是註釋掉numbers = scan.nextInt();和使用below--

// numbers = scan.nextInt(); //comment out this call 

    while ((numbers = scan.nextInt()) != 0) { 
    .... 

這會給你想要的output--

Enter an integer (0 to quit): 9 
4 
-9 
1 
0 
The number of positives is: 3 
The number of negatives is: 1 
The number of total is: 5.0