需要输入数组直到用户输入0 JAVA [英] Need To Take Input To Array Until User Enters 0 JAVA
问题描述
我需要帮助理解如何编写一个接受一定数量整数的for循环(必须是1到10)并且一旦输入0就停止接收数字(0将是最后一个数字)。到目前为止我的代码是:
I need help understanding how to write a for loop that takes in a certain amount of integers (must be 1 through 10) and it stops taking in numbers once 0 is entered (0 will be the last number). My code so far is:
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,并且然后循环停止接收数组的输入。
I don't understand how to simultaneously initialize an array with a set length while having the Scanner read a certain amount of digits of that unknown length, until 0 is entered, and then the loop stops taking in input for the array.
感谢您的帮助!
推荐答案
好了这里更详细一点: -
Ok here's the bit more detail: -
-
你需要使用
ArrayList
如果你想要一个动态增加的数组。你这样做: -
You need to use an
ArrayList
if you want a dynamically increasing array. You do it like this: -
List<Integer> numbers = new ArrayList<Integer>();
现在,在上面的代码中,您可以输入号码
在while循环中读取语句( nextInt
),因为你想要定期阅读它。并在while循环中放入一个条件来检查输入的数字是否为int: -
Now, in your above code, you can put your number
reading statement (nextInt
) inside the while loop, since you want to read it regularly. And put a condition in while loop to check whether the entered number is an int or not: -
int num = 0;
while (scanner.hasNextInt()) {
num = scanner.nextInt();
}
此外,您可以自行搬家。只需检查数字是否为 0
。如果它不是 0
,则将其添加到 ArrayList
: -
Further, you can move on your own. Just check whether the number is 0
or not. If it is not 0
, then add it to ArrayList
: -
numbers.add(num);
如果 0
,请打破退出你的while循环。
If its 0
, break out of your while loop.
你不需要 x!= 0
条件你的while循环,因为你已经在循环中检查了它。
And you don't need that x != 0
condition in your while loop, as you are already checking it inside the loop.
这篇关于需要输入数组直到用户输入0 JAVA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!