I need to stop asking for integer inputs when zero is typed as an input and start summation immediately. My program doesn't stop when I type zero. I need it to stop and start summing up all the inputs it has gathered.
Here is what I have:
public class Inttosum {
public static void main(String[] args) {
System.out.println("Enter an integer");
Scanner kb = new Scanner(System.in);
int askool = kb.nextInt();
int sum = 0;
int score = 0;
while(askool != 0){
score = kb.nextInt();
sum += score;
}
}
}
/////////////////The final code which worked..Thank you! public class Inttosum {
public static void main(String[] args) {
System.out.println("Enter an integer");
Scanner kb = new Scanner(System.in);
int sum = 0;
int score = 0;
do {
score = kb.nextInt();
sum += score;
}while(score != 0);
System.out.print(sum);
}
}
You are checking
askool !=0
whereas in the while loop values are being referenced byscore
. Change it towhile(score != 0 && askool != 0)
do-while
You are using something called
askool
as a loop condition, but updating the variablescore
in your loop. You could use ado-while
loop. Changeto something like
Using
break
I also suggest calling
Scanner.hasNextInt()
before callingnextInt
. And, since you don't use thescore
(just thesum
) you could write it like,Which will also stop (and still
sum
allint
s) if the user enters text.