+ 1

Doubt about Scanner class

Why on creating an object of Scanner class in a loop gives an error?

12th Jan 2020, 1:26 PM
Ankur Agarwal
Ankur Agarwal - avatar
3 Answers
+ 6
In simple way get soo many inputs from user ArrayList<Integer> obj = new ArrayList<>(); Scanner sc = new Scanner(System.in); while(sc.hasNextInt()) { obj.add(sc.nextInt()); }
12th Jan 2020, 2:32 PM
Sumit Programmer😎😎
Sumit Programmer😎😎 - avatar
+ 5
Can't find the code in your profile so it's hard to answer. What are you trying to do, spawn multiple objects? Each time your loop runs, a new object is created - if the name is the same you'll encounter a runtime exception. Try declaring the Scanner object outside the loop and only change its value inside of it Scanner sc = new Scanner(System.in); String response; while(true) { response = sc.nextLine(); if(response.equalsIgnoreCase("quit") break; }
12th Jan 2020, 2:04 PM
HNNX 🐿
HNNX 🐿 - avatar
+ 1
Because if you create a new object on loop iteration it won't have a new name like ob1,ob2... So it will be ob 1st time, ob next time and so on.... So multiple objects with same name would create an error...
12th Jan 2020, 2:37 PM
#DARK_PROGRAMMER_✔
#DARK_PROGRAMMER_✔ - avatar