我试图让用户输入要输入的数字,然后输入数值然后添加所有数值。
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);
}
}
答案 0 :(得分:0)
你的while循环逻辑不正确。
while(counter == times)
只有当计数器和时间具有相同的值时,才会为真。所以如果你想输入两个数字,你的while循环甚至都不会被执行。你想要的是while循环运行直到计数器==次。所以,你的逻辑应该是
while(counter != times)
此外,您应该将计数器设置为零,而不是一个。这是因为它现在意味着您已经输入了一个您没有输入的数字。
或者,您可以使用以下代码段
while (sc.hasNextInt()) {
values += sc.nextInt()
}
这个简单的循环将逐个遍历命令行中输入的所有整数,直到没有下一个整数(例如你输入一个字母)。
在这种情况下,您无需询问用户他/她将输入多少个号码,您将自行查看。