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.

user121582
  • 49
  • 1
  • 1
  • 4
  • 2
    possible duplicate of [How to check if a String is a numeric type in Java](http://stackoverflow.com/questions/1102891/how-to-check-if-a-string-is-a-numeric-type-in-java) – Madhawa Priyashantha Jul 30 '15 at 15:00
  • 1
    I think this might be what you are looking for http://stackoverflow.com/questions/5333110/checking-input-type-how – Avery B Jul 30 '15 at 15:00

6 Answers6

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"));
brso05
  • 13,142
  • 2
  • 21
  • 40
  • 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? – user121582 Jul 30 '15 at 22:15
  • 1
    `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`. – brso05 Jul 31 '15 at 12:27
  • 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. –  Jul 31 '15 at 14:21
  • Man up and say why atleast. You really shouldn't be on SO if you are going to downvote correct answers. – brso05 Aug 28 '15 at 15:06
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"));
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.

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

carcaret
  • 3,238
  • 2
  • 19
  • 37
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."); 

-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')
}
Harry
  • 1,362
  • 12
  • 19
  • There is no need for using regular expressions in this instance, that over complicates the solution. –  Jul 31 '15 at 14:22
  • 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. – Harry Jul 31 '15 at 16:04