-1

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;however, I have no idea what the condition would be since the scanner is tied to (system.in) instead of a file so it is accepting random user input rather than a predefined string. Can anyone offer advice? Here is the current code I've tried to use:

int number = 0;

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

I am getting a message that literally only reads ("compiler error") while not understand what is going on. I understand that hasnext will not work, but even if I remove it I get the same compile error message; furthermore, I'm not sure what while condition to use without the hasNext method.

I tried changing to input.hasNextLine since two people suggest it may be an EOF reached error, but I'm still getting a compiler error.

  • possible duplicate of [reading input till EOF in java](http://stackoverflow.com/questions/13927326/reading-input-till-eof-in-java), or [while EOF in JAVA?](http://stackoverflow.com/questions/8270926/while-eof-in-java) – chickity china chinese chicken Mar 01 '17 at 18:43
  • Possible duplicate of [while EOF in JAVA?](http://stackoverflow.com/questions/8270926/while-eof-in-java) – Renats Stozkovs Mar 01 '17 at 18:55
  • The solution for that seemed to be adding Line after the .hasnext method, but that didn't solve the issue. – Noah Estes Mar 01 '17 at 19:00

1 Answers1

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

    }