gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:58:25 33 4
gpt4 key购买 nike

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

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com