Java 如何使用while语句添加多个值?
我试图要求用户输入多少数字,然后输入值,然后添加所有值Java 如何使用while语句添加多个值?,java,sum,Java,Sum,我试图要求用户输入多少数字,然后输入值,然后添加所有值 import java.util.Scanner; public class sum { static Scanner sc = new Scanner(System.in); public static void main(String[] args){ int counter = 1; int values = 0; int times; Syste
import java.util.Scanner;
public class sum {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args){
int counter = 1;
int values = 0;
int times;
System.out.println("How many numbers will you input?: ");
times = sc.nextInt();
while(counter == times){
System.out.println("Enter your number: ");
values = values + sc.nextInt();
counter ++;
}
System.out.println("Your sum is " + values);
}
}
while循环的逻辑不正确
while(counter == times)
仅当计数器和时间具有相同的值时才为真。所以如果你想输入两个数字,你的while循环甚至不会被执行。您希望while循环运行到counter==次。所以,你的逻辑应该是
while(counter != times)
此外,您应该将计数器从零开始,而不是从一开始。这是因为它现在意味着你已经输入了一个号码,而你没有
或者,您可以使用以下代码段
while (sc.hasNextInt()) {
values += sc.nextInt()
}
这个简单的循环将逐个遍历命令行中输入的所有整数,直到没有下一个整数(例如键入字母)
在这种情况下,您无需询问用户将输入多少数字,您可以自己检查。谢谢您的帮助。顺便问一下,有没有其他方法要求用户输入多个数字而不设置“您将输入多少个数字?”基本上,在没有“时间”变量的情况下,添加用户输入的所有数字。是的,您可以执行以下操作:
while(sc.hasNextInt()){values+=sc.nextInt();}
@jyr您可以用您在评论中提供的代码更新您的答案,这对未来的读者来说是个好建议。就这么做了!