1

I'm new to do while loops.

I've attempted to create a do-while loop that checks if the users input is an integer or the character x. If it is neither it prompts the user to try again.

The loop instead prompts the user twice:

Intended output:

Enter answer:
500
//program is succesful

Actual output:

Enter answer:
500
//prompts user for more input

Code:

    do {
        System.out.println("Enter answer: ");
        input = scan.next();
        if(input.trim().equals("x"))
        {
            terminate = false;
            break;
        }
        while (!scan.hasNextInt()) {
            input = scan.next();
            System.out.println(input + " is not a interger!!");
        }
        operationResult = scan.nextInt();
        valid = false;
    } while (valid);
2
  • Well, you call next(), to get the next token and compare it to "x", then you call nextInt(), to get a number. Call next() only once, check if it's "x", and if it's not, try parsing it as an integer. Commented Apr 7, 2018 at 13:51
  • Thanks, I knew that I could use a try catch method as well , then do parsing there. I was hoping there was another way to do it without parsing. Commented Apr 7, 2018 at 13:54

2 Answers 2

1

You could always use a try...catch but I think this will be better -

do{
    if(scan.hasNextInt()){
        operationResult = scan.nextInt();
        break;
    }else if(scan.next().trim().equals("x")){
        break;
    }else{
        System.out.println("Enter an Integer!!");
    }
}while(true);

It checks whether its an integer first, so there's no need of a try...catch

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this is exactly what I was looking for!
0

You can use as given below: It will not check for integer value, however it will check for numeric value entered, may this will help

   public class SomeClass {
    public static void main(String args[]) {
        try (Scanner scan = new Scanner(System.in)) {
            do {
                String str = scan.next();
                if (isNumeric(str)) {
                    System.out.println("Program Ends");
                    break;
                } else if (str.equalsIgnoreCase("x")) {
                    System.out.println("Program Ends");
                    break;
                } else {
                    System.out.println("Enter Again");
                }
            } while (true);
        }
    }

    public static boolean isNumeric(String str) {
        return !str.matches(".*[^0-9].*");
    }
}

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.