reading from console with scanner in a loop for

后端 未结 2 1760
别跟我提以往
别跟我提以往 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<Integer> list = new ArrayList<Integer>();
    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();
    }
    
    0 讨论(0)
  • 2021-01-20 18:29

    Firstly, use one scanner rather than recreating a scanner every time. Also, your for loop loops one extra time.

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

    This works fine for me, at the end the List contains all the numbers I entered.

    You can test it by printing the list:

    System.out.println(list);
    

    The problem with your old code is that when you use .close() on the Scanner, it closes the underlying InputStream, which is System.in. If you close System.in, you cannot use it again in the next Scanner. This is why using one Scanner fixes the issue.

    0 讨论(0)
提交回复
热议问题