I have to enter an unknown amount of numbers using a scanner. Once the user enters -1, the program needs to print the sum of all the numbers entered and then end the program. The -1 needs to be included in the sum.
Scanner scanner = new Scanner(System.in);
int sum = 0;
while (true) {
int read = scanner.nextInt();
if (read == -1) {
break;
}
read = scanner.nextInt();
sum += read;
}
System.out.println(sum);
I can't get the correct sum. Can someone help please?
In your while loop you're assigning read
two times using scanner.nexInt()
and this breaks your logic.
Scanner scanner = new Scanner(System.in);
int sum = 0;
while (true) {
int read = scanner.nextInt();
if (read == -1) {
sum += read; //have to include -1 to sum
break;
}
//read = scanner.nextInt(); you have to delete this line
sum += read;
}
System.out.println(sum);
}
Scanner scanner = new Scanner(System.in);
int sum = 0;
int read = 0;
while (read != -1) {
read = scanner.nextInt();
sum += read;
}
scanner.close();
System.out.println(sum);
This works in my case. Closing the scanner will remove the warning too.
The following program will add -1 also in your sum. You are reading read = scanner.nextInt();
two times.
Scanner scanner = new Scanner(System.in);
int sum = 0;
while (true) {
int read = scanner.nextInt();
sum += read;
if (read == -1) {
break;
}
}
System.out.println(sum);
}
This should work
Scanner key = new Scanner(System.in);
int sum = 0;
int read;
while(read != -1) {
read = key.nextInt();
sum += read;
}
System.out.println("Sum is: " + sum);
You can't just specify while(true/false) you have to give the loop a proper expression so it can work
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.