Reputation: 35
I need to write a program that asks for integers and loops until the input is a negative integer, when the program will then end. Additionally, the loop needs to count the total number of positive integer entries and add all of the entries together. The count portion of the code seems to work fine, but my approach to getting the sum of all entries is NOT working.
What I have tried in my code is to put total=total+input at the end of my loop, but this isn't giving the correct sum when tested.
Additionally, my type safe block only works for the first entry; if I enter a letter after an integer, it crashes the program. Shouldn't that loop back to the type safe block at the beginning of each entry?
I pasted a copy of my output at the bottom.
Any help would be appreciated.
int count = 0;
int total = 0;
Scanner scan = new Scanner(System.in);
System.out.print( "Enter an integer, negative to quit: " );
while(!scan.hasNextInt())
{
scan.nextLine();
System.out.println( "That is not an integer." );
System.out.println( "Please enter an integer." );
}
int input = scan.nextInt();
while (input >= 0)
{
System.out.print( "Next integer: " );
input = scan.nextInt();
count++;
total = total + input;
}
System.out.println( "Count: " + count );
System.out.println( "Total: " + total );
When I run my code, I get the following output:
run:
Enter an integer, negative to quit: h
That is not an integer.
Please enter an integer:
1
Next integer: 2
Next integer: 3
Next integer: -1
Count: 3
Total: 4
BUILD SUCCESSFUL (total time: 10 seconds)
Upvotes: 0
Views: 82
Reputation: 1
Swap the order of operations. First sum and count, then get a new input:
while (input >= 0) {
total = total + input;
count++;
System.out.print("Next integer: ");
input = scan.nextInt();
}
Your current code discards the first input 1
and starts summing and counting with the second input 2
.
Upvotes: 2
Reputation: 5185
You need to check on each iteration if the next entry is an integer
or not. Aditionally you need to sum the initial integer
before you ask for the next one:
int input = 0;
int count = 0;
int total = 0;
do{
System.out.print("Enter an Integer: ");
total += input;
if(!scan.hasNextInt()) {
scan.nextLine();
System.out.println( "That is not an integer." );
input = 0;
} else {
input = scan.nextInt();
count++;
}
} while(input >= 0);
System.out.println("Count: " + (count - 1));
System.out.println("Total: " + total);
Upvotes: 1