如何读整数,并将它们存储在Java中的数组 [英] how to read integers and store them in an array in java
本文介绍了如何读整数,并将它们存储在Java中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
很抱歉,如果这是一个明显的问题。
Sorry if this is an obvious problem.
我想从用户读取整数,并将它们存储在数组中。
I'm trying to read integers from users and store them in an array.
的事情是,我想使用ArrayList,因为输入的大小是不肯定的。
The thing is that I want to use arraylist, because the size of the input is not for sure
如果我知道的大小,然后我知道的方式做到这一点,这是
If I know the size then I know a way to do that, which is
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代替扫描仪?
How to do this if I don't know the size? Except for reading one number in each loop, is there any better way to do that? Can I use BufferedReader instead of 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);
}
这篇关于如何读整数,并将它们存储在Java中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文