2017-03-01 13 views
-1

私は、inputという名前のスキャナ変数とtotalという名前の整数変数を使用して、入力内のすべての整数値を受け入れ、それらを合計する必要があるMyProgrammingLabの問題を解決しようとしています。 。プログラムはwhileループを推奨していますが、ファイルの代わりにスキャナが(system.in)に結びついているため、条件がどうなっているか分かりませんので、あらかじめ定義された文字列ではなくランダムな入力を受け付けます。誰でもアドバイスを提供できますか?ここで私が使用しようとした現在のコードは次のようになります。Java Input/output MyProgrammingLab 21212

int number = 0; 

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

私は何が起こっているか理解していながら、文字通りのみ(「コンパイルエラー」)を読み込み、メッセージを取得しています。 hasnextはうまくいきませんが、削除しても同じコンパイルエラーメッセージが表示されます。さらに、hasNextメソッドなしで使用する条件が何であるかわからない。

私はinput.hasNextLineに変更しようとしました。なぜなら、2人の人がEOFに達したというエラーがあるかもしれないと示唆しているからですが、まだコンパイラーエラーが出ています。

+0

[JavaでEOFまで読み出す入力(http://stackoverflow.com/questions/13927326/reading-input-till-eof-in-java)の可能な重複、または[EOF JAVAにある間? ](http://stackoverflow.com/questions/8270926/while-eof-in-java) – davedwards

+0

[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"); 

    } 
関連する問題