-6

I am a noob in programming. I wanted to write code for a prog which asks user to enter value until an integer is entered.

public class JavaApplication34 {

    /**
    * @param args the command line arguments
    */
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int flag = 0;
        while(flag == 0) {
            int x = 0;
            System.out.println("Enter an integer");

            try {
                x = sc.nextInt();
                flag = 1;
            } catch(Exception e) {
                System.out.println("error");        
            }

            System.out.println("Value "+ x);
        }
    }
}

I think the code is correct and it should ask me to enter the value again if i have entered anything other than an integer. But when i run it , and say i enter xyz it iterates infinite time without asking me to enter the value.

test run :
Enter an integer
xyz
error
Value 0
Enter an integer
error
Value 0
Enter an integer
error
Value 0
Enter an integer
error
Value 0
Enter an integer
error
Value 0
Enter an integer
error
Value 0
Enter an integer
error
Value 0
Enter an integer
error
Value 0
Enter an integer
error
Value 0
4
  • 1
    In a catch block such as your catch(Exception e){, the e holds valuable information about what happened. Use e.printStackTrace() to find out more. Commented May 9, 2017 at 13:59
  • 7
    Your flag is very sad because it wants to be boolean. Commented May 9, 2017 at 14:04
  • why??? please help Commented May 9, 2017 at 14:07
  • @MridulMittal read the answer posted by T.J. Crowder Commented May 10, 2017 at 13:52

4 Answers 4

4

When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception.

Hence sc.nextInt() reads the same token again and throws the same exception again.

...
...
...
catch(Exception e){
     System.out.println("error");
     sc.next(); // <---- insert this to consume the invalid token
}
Sign up to request clarification or add additional context in comments.

Comments

2

You can change your logic as shown below :

    int flag = 0;
    int x = 0;
    String str="";
    while (flag == 0) {         
        System.out.println("Enter an integer");
        try {
            str = sc.next();
            x = Integer.parseInt(str);
            flag = 1;
        } catch (Exception e) {
            System.out.println("Value " + str);
        }           
    }

Here we have first read the input from Scanner and then we are trying to parse it as int, if the input is not an integer value then it will throw exception. In case of exception we are printing what user has enter. When user enters an integer then it will parsed successfully and value of flag will update to 1 and it will cause loop to exit.

Comments

1

In the error case, you need to clear out the string you've entered (for instance, via nextLine). Since it couldn't be returned by nextInt, it's still pending in the scanner. You also want to move your line outputting the value into the try, since you don't want to do it when you have an error.

Something along these lines:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    int flag = 0;
    while(flag == 0)
    {
        int x = 0;
        System.out.println("Enter an integer");
        try
        {
            x = sc.nextInt();
            flag = 1;
            System.out.println("Value "+ x);
        }
        catch (Exception e){
            System.out.println("error");
            if (sc.hasNextLine()) { // Probably unnecessary
                sc.nextLine();
            }
        }
    }
}

Side note: Java has boolean, there's no need to use int for flags. So:

boolean flag = false;

and

while (!flag) {

and

flag = true; // When you get a value

4 Comments

can you help ??
@MridulMittal: That is help.
If you will not try to solve them on your own even after knowing the error, You will remain a NOOB.
@MridulMittal: The best way, by far, to become a non-n00b is to work things through. But I've added an example of what you might do above.
0

The answers to this question might help you

It makes use of Scanners .hasNextInt() function!

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.