4

I was wondering how you can do type checking for a user input. Here I have a simple test to check if the user input is between 1 and 10. I want to set it up so that the user can also enter a letter, primarily so I can use the input 'q' to quit the program.

Is there a part of the scanner that can type check? My thought was to have an if statement: if user inputs type int continue, if it is not type int, check if it is q to quit the program, else output this is an error. Below is what I have so far, it throws an expression when a number is put in since the types do not match.

public static void main(String[] args) {
    //Create new scanner named Input
    Scanner Input = new Scanner(System.in);
    //Initialize Number as 0 to reset while loop
    int Number = 0;

    do
    {
        //Ask user to input a number between 1 and 10
        System.out.println("At anytime please press 'q' to quit the program.");
        System.out.println();
        System.out.print("Please enter a number between 1 and 10:");
        Number = Input.nextInt();

        if (Number == 'Q'|| Number == 'q')
        {
            System.out.println("You are now exiting the program");
        }
        else if (Number >= 1 && Number <= 10)
        {
            System.out.println("Your number is between 1 and 10");
        }   
        else
        {
            System.out.println("Error: The number you have entered is not between"
                    + " 1 and 10, try again");
        }
    }
    //Continue the loop while Number is not equal to Q
   while (Number != 'Q' & Number != 'q');
}

}

Thanks everyone for the responses. I am a bit new so the try statement is new to me but looks like it will work (seems somewhat self explanatory of what it does). I will look into its use more and implementing it correctly.

2

6 Answers 6

1

I would use nextLine() and parseInt() to see if it is an int:

    int Number;
    String test = "";
    boolean isNumber = false;
    ......

    test = Input.nextLine();
    try
    {
        Number = Integer.parseInt(test);
        isNumber = true;
    }
    catch(NumberFormatException e)
    {
         isNumber = false;
    }
    if(isNumber)
    {
        if (Number >= 1 && Number <= 10)
        {
            System.out.println("Your number is between 1 and 10");
        }   
        else
        {
            System.out.println("Error: The number you have entered is not between"
                + " 1 and 10, try again");
        }
    }
    else
    {
        if (test.equalsIgnoreCase("q"))
        {
            System.out.println("You are now exiting the program");
        }
    }

.........
while (!test.equalsIgnoreCase("q"));
Sign up to request clarification or add additional context in comments.

4 Comments

Does the catch statement always have the e? This is the only thing I am a bit fuzzy on. I am understanding everything else there but the e is throwing me off a bit, is it just part of the syntax?
e could be anything...it could be catch(NumberFormatException ex) it could be catch(NumberFormatException exception) it could be catch(NumberFormatException anything). It is just a variable you are passing to the catch block. Inside the catch block it will hold information pertinent to the exception thrown such as the StackTrace.
To clarify the above comment the 'e' is the variable name for that instance of the exception. You can then do stuff with the instance of the exception if necessary (eg e.getStackTrace). The name is inconsequential for your purpose.
Man up and say why atleast. You really shouldn't be on SO if you are going to downvote correct answers.
1

try this

    Scanner Input = new Scanner(System.in);
    //Initialize Number as 0 to reset while loop
    String Number = "0";

    do {
        try {
            //Ask user to input a number between 1 and 10
            System.out.println("At anytime please press 'q' to quit the program.");
            System.out.println();
            System.out.print("Please enter a number between 1 and 10:");
            Number = Input.next();

            if (Number.equalsIgnoreCase("q")) {
                System.out.println("You are now exiting the program");
            } else if (Integer.valueOf(Number) >= 1 && Integer.valueOf(Number) <= 10) {
                System.out.println("Your number is " + Number);
            } else {
                System.out.println("Error: The (" + Number + ") is not between 1 and 10, try again");
            }
        } catch (NumberFormatException ne) {
            System.out.println("Error: The (" + Number + ") is not between 1 and 10, try again");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    } //Continue the loop while Number is not equal to Q
    while (!Number.equalsIgnoreCase("q"));

Comments

0

Have your input read in as a string, to check for the input of Q/q. Then after that you can parseInt from input string to integer in a way as follows, catching potential NumberFormatExceptions.

String input = "5"
try {
int number = Integer.parseInt(input);
} catch (NumberFormatException e) {
System.out.println("Not a number!") 
}

Or something similar to that.

Comments

0

You could check if it's an int this way:

String inputArg = Input.next();

private boolean isInt(String inputArg){
    boolean isInt = true;
    try {
         Integer.parseInt(inputArg);
    } catch(NumberFormatException e) {
         isInt = false;
    }
    return isInt;
}

Other way is using regular expressions

Comments

0

Found this piece of code check it out, it worked for me.

          Scanner input = new Scanner (System.in);
          if (input.hasNextInt()) {
              int a = input.nextInt();
              System.out.println("This input is of type Integer."+a);
          }   
                   
          else if (input.hasNextLong())
            System.out.println("This input is of type Long.");
       
          else if (input.hasNextFloat())
          System.out.println("This input is of type Float.");
          
          else if (input.hasNextDouble()) 
          System.out.println("This input is of type Double."); 
           
          else if (input.hasNextBoolean())
           System.out.println("This input is of type Boolean.");  
          
          else if (input.hasNextLine())
              System.out.println("This input is of type string."); 

Comments

-1

You could get the input as a String and then use regular expression matching on the said String.

String txt = Input.nextLine();
if(txt.matches("[0-9]+") // We have a number
{
   // Safe to parse to number
}
else if(txt.matches("[A-Za-z]+") // We have alphabeticals
{
   // Check for various characters and act accordingly (here 'q')
}

2 Comments

There is no need for using regular expressions in this instance, that over complicates the solution.
I'm going to have to disagree with you there. I don't think it adds much complexity at all, is more versatile and doesn't rely on exception handling for the program flow.

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.