如何读取整数并将其存储在java中的数组中
问题描述:
对不起,如果这是一个明显的问题。如何读取整数并将其存储在java中的数组中
我试图从用户读取整数并将它们存储在一个数组中。
的事情是,我想使用ArrayList,因为输入的大小是不肯定的
如果我知道的大小,然后我知道的方式做到这一点,这是
class Test1
{
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
System.out.println("Please input your numbers");
int num; // integer will be stored in this variable
ArrayList<Integer> List = new ArrayList<Integer>();
// for example if I know the size of the input is 5,
// then I read one single number and put it into the arraylist.
for (int i = 0; i <= 4; i++)
{
num = reader.nextInt();
List.add(num);
}
System.out.println(List);
}
}
如果我不知道尺寸,怎么做? 除了在每个循环中读取一个数字,有没有更好的方法来做到这一点? 我可以使用BufferedReader而不是Scanner吗?
非常感谢您的帮助!
答
你可以改变这个
for (int i = 0; i <= 4; i++)
{
num = reader.nextInt();
List.add(num);
}
使用Scanner.hasNextInt()
喜欢的东西
while (reader.hasNextInt())
{
num = reader.nextInt();
List.add(num);
}
答
你不能实例化一个数组,如果你不知道它的大小。
因此,您的方法是正确的:从ArrayList
开始,添加完成后,可以将其转换为数组。
+0
谢谢你的帮助! – Ahaha 2014-10-16 19:28:18
答
您可以在while循环中使用hasNextInt()
继续前进,直到没有更多数字要读取。
while (reader.hasNextInt()) {
List.add(reader.nextInt());
}
谢谢。整数已成功添加。但为什么我需要结束程序来查看输出? – Ahaha 2014-10-16 19:22:02
无论如何问题解决了,非常感谢! – Ahaha 2014-10-16 19:29:30
@Ahaha尝试输入任何非数字值(如“停止”或“退出”)。 – 2014-10-16 22:52:55