0

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
              }
3
  • 3
    How can a Scanner Object be equals to a negative int ? Commented Oct 18, 2017 at 5:19
  • 1
    input from a scannershould be Commented Oct 18, 2017 at 5:20
  • 1
    Then please show me how to do it correctly Commented Oct 18, 2017 at 5:25

4 Answers 4

1

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();
Sign up to request clarification or add additional context in comments.

Comments

1

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
}

1 Comment

Thank you so much! I understood what i was doing wrong! This worked for me!
1

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!

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.