简体   繁体   English

如何读取整数并将其存储在Java中的数组中

[英]how to read integers and store them in an array in java

Sorry if this is an obvious problem. 抱歉,这是一个明显的问题。

I'm trying to read integers from users and store them in an array. 我正在尝试从用户读取整数并将其存储在数组中。

The thing is that I want to use arraylist, because the size of the input is not for sure 事实是我想使用arraylist,因为不确定输入的大小

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);
    }
}

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? 我可以使用BufferedReader代替Scanner吗?

Thanks a lot for any help! 非常感谢您的帮助!

You could change this 你可以改变这个

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

to use Scanner.hasNextInt() with something like 使用Scanner.hasNextInt()与类似

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

You cannot instanciate an array if you do not know its size. 如果您不知道数组的大小,则无法实例化它。

Therefore your approach is the correct one: start with an ArrayList and when done adding to it, you can convert it to an array. 因此,您的方法是正确的方法:从ArrayList开始,完成添加后,可以将其转换为数组。

You can use the hasNextInt() in a while loop to keep going until there are no more numbers to read. 您可以在while循环中使用hasNextInt()继续进行下去,直到没有更多的数字可读取为止。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM