Search code examples
javasumuser-input

Adding 3 User Input Numbers together


I am doing an exercise from a site where I am trying to add 3 numbers the user inputs only using three variables. The code they let you start off with is:

Scanner reader = new Scanner(System.in);
int sum = 0;
int read;

// WRITE YOUR PROGRAM HERE
// USE ONLY THE VARIABLES sum, reader AND read!

System.out.println("Sum: " + sum);

I was thinking of using a for loop but I keep getting stuck because I can only use three variables. reader is already being used by Scanner. sum is going to be changing values, and read is going to be a temporary value.

I would have used

System.out.println("Enter a number: ");
int read = Integer.parseInt(reader.nextLine());

But that would have only held 1 number. Any help I've been stuck on this for a while.


Solution

  • This should satisfy the requirement:

    for(read = 3; read > 0; read--) {
        System.out.println("Enter a number: ");
        sum += Integer.parseInt(reader.nextLine());
    }