我需要帮助理解如何编写一个 for 循环,它接受一定数量的整数(必须是 1 到 10),并且一旦输入 0,它就会停止接受数字(0 将是最后一个数字)。到目前为止我的代码是:
import java.util.Scanner;
public class countNum {
public static void main(String[] args) {
int[] array;
Scanner input = new Scanner(System.in);
System.out.println ("Enter in numbers (1-10) enter 0 when finished:");
int x = input.nextInt();
while (x != 0) {
if (x > 2 && x < 10) {
//Don't know what to put here to make array[] take in the values
}
else
//Can I just put break? How do I get it to go back to the top of the while loop?
}
}
}
}
我不明白如何同时初始化具有设定长度的数组,同时让扫描仪读取一定数量的未知长度的数字,直到输入 0,然后循环停止接受数组的输入。
谢谢你的帮助!
好的,这里有更多细节:-
-
你需要使用一个ArrayList
如果你想要一个动态增加的数组。你这样做:-
List<Integer> numbers = new ArrayList<Integer>();
-
现在,在上面的代码中,您可以将number
阅读陈述(nextInt
) 在 while 循环内,因为您想定期阅读它。并在 while 循环中添加一个条件来检查输入的数字是否为 int:-
int num = 0;
while (scanner.hasNextInt()) {
num = scanner.nextInt();
}
-
此外,您还可以自行移动。只需检查号码是否为0
或不。如果不是0
,然后将其添加到ArrayList
: -
numbers.add(num);
If its 0
,跳出 while 循环。
你不需要那个x != 0
while 循环中的条件,因为您已经在循环内检查它。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)