java - 接受一系列数字? for循环

标签 java loops for-loop numbers

我是编程新手,所以我不知道如何编写一个接受一系列数字的程序,并且仅当用户输入 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/

相关文章:

r - 如何在R中使用map迭代对象以创建一系列gt表

swift - 在 swift 中表达具有动态范围的 for 循环

javascript - 为什么循环保持两个变量相等?

java - 如何在 Java 中正确地将值添加到 3D 数组

java - 使用 mongo 响应式(Reactive) Spring 检查 Webflux 数据

ruby-on-rails - 在 Ruby 中逐一堆叠

c++ - 有没有办法简化这个 C++ 整数循环数组?

java - Tomcat 7 到 8.5 升级 : getResourceAsStream throws NPE

java - ForkJoinPool 中有多少个线程 worker ?

java - 如何在 SWT 中使用标准尺寸制作可调整大小的布局