2017-03-01 115 views
-1

我想解決MyProgrammingLab中的一個問題,其中我必須使用名爲input的掃描器變量和名爲total的整數變量來接受輸入中的所有整數值,並將它們放入總計。該程序建議使用while循環;但是,我不知道條件是什麼,因爲掃描器與(system.in)綁定,而不是文件,因此它接受隨機用戶輸入而不是預定義的字符串。任何人都可以提供意見下面是當前代碼我試着使用:Java輸入/輸出MyProgrammingLab 21212

int number = 0; 

while (input.hasNext()) 
{ 
     number = input.nextInt(); 
     total = number; 
} 

我得到一個消息,從字面上只讀取(「編譯器錯誤」),而不是明白是怎麼回事。我明白,hasnext不起作用,但即使我刪除它,我也會得到相同的編譯錯誤信息;此外,我不確定在沒有hasNext方法的情況下使用什麼條件。

我試着改變input.hasNextLine,因爲兩個人建議它可能是一個EOF到達錯誤,但我仍然收到編譯器錯誤。的[讀取輸入直到EOF在Java]

+0

可能重複(http://stackoverflow.com/questions/13927326/reading-input-till-eof-in-java),或[而EOF在JAVA? ](http://stackoverflow.com/questions/8270926/while-eof-in-java) – davedwards

+0

[while while EOF in JAVA?]可能重複(http://stackoverflow.com/questions/8270926/while-eof- in-java) – bc004346

+0

解決方案似乎是在.hasnext方法之後添加Line,但這並沒有解決問題。 –

回答

0
/* 
I am trying to solve a problem in MyProgrammingLab in which I must use a scanner variable named input, 
and an integer variable named total, to accept all the integer values in input, and put them into total. 
The program recommends a while loop; 
*/ 

private static Scanner input; //Collect user numbers 
private static int total = 0; // to display total at end 
private static int number = 0; // Variable to hold user number 
private static boolean loopCheck = true; // Condition for running 

public static void main(String[] args) { 
    // Main loop 
    while(loopCheck) { 
     input = new Scanner(System.in); // Setting up Scanner variable 

     // Information for user 
     System.out.println("Enter 0 to finish and display total"); 
     System.out.println("Enter an Integer now: "); 

     number = input.nextInt(); // This sets the input as a variable (so you can work with the information) 
     total += number; // total = (total + number); Continually adds up. 

     // When user inputs 0, changes boolean to false, stops the loop 
     if(number == 0) { 
      loopCheck = false; 
     } 

    } 
    //Displays this when 0 is entered and exits loop 
    System.out.println("Your total is: " + total); // Displays the total here 
    System.out.println("Program completed"); 

    }