Reputation: 133
What is the correct syntax to get Integers from scanner if they meet some criteria and assign to arrayList? It should loop and get the inputs until we insert "-1". It stops then I insert "q" but I need it to work with certain integer.
Scanner sc = new Scanner(System.in);
while (-99 !== sc.nextLine() && sc.hasNextInt())
{
//do something Whi
}
Upvotes: 0
Views: 123
Reputation: 844
This will loop until -1 is encountered, and add the elements to the arraylist. Let me know if you need any help in this.
List<Integer> list = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
// keep looping until -1 is encountered
while (true) {
int temp = scanner.nextInt();
if (temp == -1) {
break;
}
list.add(temp);
}
// Printing the array list
System.out.println(list);
// closing the scanner is important
scanner.close();
Upvotes: 1
Reputation: 21
sc if a refrence to a object of Scanner class and not compaire with int object. you must check the value of next int in your while loop
Upvotes: 0
Reputation: 375
You probably want to do this:
Scanner sc = new Scanner(System.in);
int num;
do{
while (!sc.hasNextInt()){
sc.next();
}
num = sc.nextInt();
}while(num!=-1)
Hope this helps!
Upvotes: 1
Reputation: 44834
I am not sure exactly what your requirements are but how about
Scanner sc = new Scanner(System.in);
while (true)
{
int numEntered = sc.nextInt ();
if (numEntered == -1) {
break;
}
// do something
}
Upvotes: 1