3

I'm trying to set up a do-while loop that will re-prompt the user for input until they enter an integer greater than zero. I cannot use try-catch for this; it's just not allowed. Here's what I've got:

Scanner scnr = new Scanner(System.in);
int num;
do{
System.out.println("Enter a number (int): ");
num = scnr.nextInt();
} while(num<0 || !scnr.hasNextLine());

It'll loop if a negative number is inputted, but if a letter is, the program terminates.

3
  • Have either of our answers helped you? Commented Feb 16, 2014 at 23:34
  • This is for an introductory class project (hence why I can't use try-catch--because we haven't learned it), and I don't know if we're allowed to use parseInt(). It makes sense to me, and I'm going to try to implement it now. Thanks, guys. Commented Feb 16, 2014 at 23:37
  • If you can't use try-catch and you can't use string regex/parseInt then you're doing a ridiculous project. Commented Feb 16, 2014 at 23:47

2 Answers 2

5

You can take it in as a string, and then use regex to test if the string contains only numbers. So, only assign num the integer value of the string if it is in fact an integer number. That means you need to initialize num to -1 so that if it is not an integer, the while condition will be true and it will start over.

Scanner scnr = new Scanner(System.in);
int num = -1;
String s;
do {
    System.out.println("Enter a number (int): ");
    s = scnr.next().trim(); // trim so that numbers with whitespace are valid

    if (s.matches("\\d+")) { // if the string contains only numbers 0-9
        num = Integer.parseInt(s);
    }
} while(num < 0 || !scnr.hasNextLine());

Sample run:

Enter a number (int): 
-5
Enter a number (int): 
fdshgdf
Enter a number (int): 
5.5
Enter a number (int): 
5
Sign up to request clarification or add additional context in comments.

Comments

3

As using try-catch is not allowed, call nextLine() instead
of nextInt(), and then test yourself if the String you got
back is an integer or not.

import java.util.Scanner;

public class Test038 {

    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);
        int num = -1;
        do {
            System.out.println("Enter a number (int): ");
            String str = scnr.nextLine().trim();
            if (str.matches("\\d+")) {
                num = Integer.parseInt(str);
                break;
            }

        } while (num < 0 || !scnr.hasNextLine());
        System.out.println("You entered: " + num);
    }

}

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.