user1554786 user1554786 - 1 month ago 4
Java Question

How many integers, addition of integers

import java.util.Scanner;
public class InputLoop
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer to continue or a non integer to finish");

while (scan.hasNextInt())
{
System.out.println("Enter an integer to continue or a non integer to finish");
int value = scan.nextInt();
System.out.print("user: ");
}
scan.next();
{
System.out.println ("You entered");
System.out.println ();

}
}


}

Where it says 'you entered' I have to have how many Integers have been input, for example '3' and then the total of the integers added together for example '56'. I don't know how to do this, how can I implement this?

jbx jbx
Answer

Just keep a variable named count and a variable named sum. And change your code in the while loop to:

 int value = scan.nextInt();
 sum += value;
 count++;

In the end you can output both after the while loop ends.

By the way you don't need to put those curly braces { } after scan.next(); They're unrelated, and will always be executed independently of scan.next();

So just change it to:

scan.next();  //I presume you want this to clear the rest of the buffer?
System.out.println("You entered " + count + " numbers");
System.out.println("The total is " + sum);
Comments