我是编程新手,所以我不知道如何编写一个接受一系列数字的程序,并且仅当用户输入 0 时才会退出,然后显示在用户输入 0 之前输入了多少个数字.
我的代码:
import java.util.Scanner;
class Sample {
public static void main(String[]args) {
Scanner x = new Scanner(System.in);
int y;
int count = 0;
System.out.print("Enter any number to continue. Enter 0 to stop.");
num = x.nextInt();
for(int n = 0; n<=num; n++) { //is this for loop right?
y = x.nextInt();
count += y;
}
if(num == 0){
System.out.printf("You entered %d numbers,count");
}
}
} // i know my code is missing alot.
输出应该是这样的。
Enter any number to continue. Enter 0 to stop
12
11
5
6
1
0
You entered 6 numbers.
2 even
3 odd // i know my code is far from what i want my output to be.
EDIT :
if the user enters 2 then 0 the output should be
You Entered an even number // same with odd. how?
最佳答案
一些线索:
你的线路
num = x.nextInt();
可能会导致编译错误,因为您尚未声明变量 num
。
此外,您的循环应该while数字大于 0 时继续。为此,请使用 while 循环:
int num = 1; //some non-zero starting number
while (num != 0) {
num = x.nextInt();
count++;
}
关于java - 接受一系列数字? for循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32740377/