reading from console with scanner in a loop for

后端 未结 2 1778
别跟我提以往
别跟我提以往 2021-01-20 17:49

i have this method, and the idea is read from the console (keyboard) a sequence of int numbers and add all of them in an ArrayList, im using the class Scanner to read the nu

2条回答
  •  情话喂你
    2021-01-20 18:22

    Your problem is here:

    Scanner sn = new Scanner(System.in);
    int n = sn.nextInt();
    sn.close();
    

    You're closing the current Scanner, which will close the InputStream used to read the data, which means your application won't accept any more input from user. That's why creating a new Scanner that will read from System.in won't work. Even if you create another kind of reader using System.in won't work.

    Usually, when dealing with System.in you create a single reader (in this case, Scanner) that will work for all the application. So, your code should look like this:

    System.out.println("Give me a size ");
    Scanner sn = new Scanner(System.in);
    int n = sn.nextInt();
    //sn.close();
    List list = new ArrayList();
    for (int i=0; i < n; ++i){
        System.out.println("Give me a number ");
        //Scanner sn2 = new Scanner(System.in);
        int in = sn.nextInt();
        list.add(in);
        //sn2.close();
    }
    

提交回复
热议问题