[英]Sum of n-amount of Integers Scanner
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.
一旦用户输入-1,程序需要打印所有输入数字的总和,然后结束程序。 The -1 needs to be included in the sum.
-1 需要包含在总和中。
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.在您的 while 循环中,您使用
scanner.nexInt()
分配了两次read
,这破坏了您的逻辑。
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.以下程序还将在您的总和中添加 -1。 You are reading
read = scanner.nextInt();
您正在阅读
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你不能只指定 while(true/false) 你必须给循环一个正确的表达式,这样它才能工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.