如何读取整数并将它们存储在java中的数组中

时间:2014-10-16 19:08:22

标签: java arrays

很抱歉,如果这是一个明显的问题。

我正在尝试从用户读取整数并将它们存储在数组中。

问题是我想使用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吗?

非常感谢您的帮助!

3 个答案:

答案 0 :(得分:2)

你可以改变这个

for (int i = 0; i <= 4; i++) 
{
  num = reader.nextInt();
  List.add(num);
}

使用类似

Scanner.hasNextInt()
while (reader.hasNextInt()) 
{
  num = reader.nextInt();
  List.add(num);
}

答案 1 :(得分:0)

如果您不知道其大小,则无法实例化数组。

因此,您的方法是正确的:从ArrayList开始,添加完成后,您可以将其转换为数组。

答案 2 :(得分:0)

您可以在while循环中使用hasNextInt()继续前进,直到没有更多数字可供阅读。

  while (reader.hasNextInt()) {
      List.add(reader.nextInt());
  }
相关问题