需要对数组进行输入,直到用户输入 0 JAVA
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13023716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Need To Take Input To Array Until User Enters 0 JAVA
提问by Zach
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:
我需要帮助理解如何编写一个接受一定数量整数(必须是 1 到 10)的 for 循环,并且一旦输入 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?
}
}
}
}
}
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.
我不明白如何在让扫描器读取一定数量的未知长度的数字的同时,同时初始化具有设定长度的数组,直到输入 0,然后循环停止接收数组的输入。
Thanks for any help!
谢谢你的帮助!
采纳答案by Rohit Jain
Ok here's the bit more detail: -
好的,这里有更多细节:-
You need to use an
ArrayList
if you want a dynamically increasing array. You do it like this: -List<Integer> numbers = new ArrayList<Integer>();
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(); }
Further, you can move on your own. Just check whether the number is
0
or not. If it is not0
, then add it toArrayList
: -numbers.add(num);
If its
0
, break out of your while loop.And you don't need that
x != 0
condition in your while loop, as you are already checking it inside the loop.
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);
如果是
0
,则跳出你的 while 循环。而且您
x != 0
的 while 循环中不需要该条件,因为您已经在循环内检查了它。
回答by npinti
In your case, the user seems to be able to input any number of digits. For this scenario, having an array is not ideal simply because the size of the array needs to be known prior to the array initialization. You have some options though:
在您的情况下,用户似乎能够输入任意数量的数字。对于这种情况,拥有数组并不理想,因为在数组初始化之前需要知道数组的大小。不过你有一些选择:
- Use an ArrayList. This a dynamic data structure which expands dynamically.
- Ask the user the amount of numbers he/she is going to be entering and use that to initialize the array.
- Create an array basing yourself on some assumption on the size.
- 使用ArrayList。这是一个动态扩展的动态数据结构。
- 询问用户他/她将要输入的数字数量并使用它来初始化数组。
- 根据对大小的一些假设创建一个数组。
In both cases 2 and 3, you would also need to include some logic that will make the program stop when: (1) The user enters 0 (2) OR when the amount of numbers provided by the user exceeds the size of the array.
在第 2 种和第 3 种情况下,您还需要包含一些使程序在以下情况下停止的逻辑: (1) 用户输入 0 (2) OR 当用户提供的数字数量超过数组的大小时。
I would recommend sticking to the first solution though since it is easier to implement.
我建议坚持第一个解决方案,因为它更容易实现。
回答by Karthikeyan Arumugam
I strongly recommend you go get some hands on with Java Collections.
我强烈建议您尝试使用 Java 集合。
you can fix your program as
你可以修复你的程序
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Scanner;
public class arrayQuestion {
public static void main(String[] args) {
List<Integer> userInputArray = new ArrayList<Integer>();
Scanner input = new Scanner(System.in);
System.out.println("Enter 10 Numbers ");
int count = 0;
int x;
try {
do {
x = input.nextInt();
if (x != 0) {
System.out.println("Given Number is " + x);
userInputArray.add(x);
} else {
System.out
.println("Program will stop Getting input from USER");
break;
}
count++;
} while (x != 0 && count < 10);
System.out.println("Numbers from USER : " + userInputArray);
} catch (InputMismatchException iex) {
System.out.println("Sorry You have entered a invalid input");
} catch (Exception e) {
System.out.println("Something went wrong :-( ");
}
// Perform Anything you want to do from this Array List
}
}
I hope this will solve your doubt.. beyond this u need to handle Exceptions if user enters any character or invalid inputs as above
我希望这能解决您的疑问..除此之外,如果用户输入任何字符或无效输入,您需要处理异常