gymcode
gymcode

Reputation: 4623

WHILE Loop Condition Does Not Validate Input

I have a WHILEloop which checks for marks for a particular student. However, it does not loop if the value is invalid (input less than 0 and more than 100):

int marks= -1;

System.out.print("Student Marks (/100): ");
                while (((marks< 0) || (marks> 100))) {
                    try {
                        marks = Integer.parseInt(sc.nextLine());
                        break;
                    } catch (NumberFormatException nfe) { 
                        System.err.println("Error: Invalid Mark(s)");
                        System.out.print("Student Marks (/100): ");
                    }
                }

It does catches exception if characters other than numbers are entered.

But it does not loop again if value if less than 0 or more than 100.

I have tried making many changes to it but to no result.

Any help given is appreciated!

Upvotes: 1

Views: 3402

Answers (3)

Razib
Razib

Reputation: 11163

You may check the marks inside the while loop with an if condition and here you may use break -

import java.util.Scanner;

public class TakeInput{ 

    public static void main(String args[]){

        int marks= -1;
        Scanner sc = new Scanner(System.in);

        System.out.print("Student Marks (/100): ");
        while (sc.hasNext()) {
            try {
                marks = Integer.parseInt(sc.nextLine());
                if(marks<0 || marks>100){
                    break;
                }
                //do something
                // with the marks

                //take new marks
                System.out.print("Student Marks (/100): ");
            } catch (NumberFormatException nfe) { 
                System.err.println("Error: Invalid Mark(s)");
                System.out.print("Student Marks (/100): ");
            }
        }
    }

}  

Now as long as you enter anything except a number n when n<0 || n>100 will continue the loop. Any NumberFormatExeption take you to the catch block.

If you enter 34 then it goes to the while block and prompt for a next number. Then if you enter 56 then it dose the same thing.
When you enter any String rather than a number than it goes to the catch block
This process continues until you enter a invalid number (n>100 || n<100). Pressing Ctrl+C also exit you from the loop.

Hope it will help you.
Thanks a lot.

Upvotes: 1

Rajesh
Rajesh

Reputation: 384

Always use continue instead of break if you want to keep the loop running.

Upvotes: 1

Eran
Eran

Reputation: 393841

You should remove the break statement, since it breaks you out of the loop regardless of what value of marks was input.

Upvotes: 6

Related Questions