Home Ask Login Register

Developers Planet

Your answer is one click away!

Nabz February 2016

Reading Numbers until condition met

I'm trying to ask the user to keep typing in numbers until they type -1 once they do the code will say Thank you see you later! I'm kind of stuck right now cause my loop is infinite loop and I'm trying to solve it without using iterations. This is what I have.

Scanner reader = new Scanner(System.in);
System.out.println("Type numbers: ");
int num = Integer.parseInt(reader.nextLine());   
while (num < -1 || num > -1) {
    System.out.println(num);   
        if (num == -1) {
        System.out.println("Thank you and see you later!");
        break;
    }

}

Answers


Chris February 2016

You need to read the input inside the loop. You're only doing it once (before entering the loop) so the value of num never changes. Also, you could simplify your while condition by using while (num != -1)

So ultimately, you'd want something like this:

Scanner reader = new Scanner(System.in);
System.out.println("Type numbers: ");
int num = 0;
while (num != -1) {
    num = Integer.parseInt(reader.nextLine());   

        if (num == -1) {
            System.out.println("Thank you and see you later!");

    }else{
       System.out.println(num);   
    }

}


Makandal February 2016

Try this code:

Scanner reader = new Scanner(System.in);
int num = 0;
System.out.println("Type numbers: ");
while(true){
    //get user input
    num = Integer.parseInt(reader.nextLine());
    if(num == -1){
        System.out.println("Thank you and see you later!");
        break;
    }
}

Post Status

Asked in February 2016
Viewed 3,794 times
Voted 4
Answered 2 times

Search




Leave an answer


Quote of the day: live life