0
import java.util.Scanner;

public class HelloWorld {
public static int num;
public static Scanner scan;
  public static void main(String[] args) {
    System.out.println("Hello World");
        /* This reads the input provided by user
         * using keyboard
         */
         scan = new Scanner(System.in);
        System.out.print("Enter any number: ");

        // This method reads the number provided using keyboard

        check();

        // Closing Scanner after the use


        // Displaying the number 
        System.out.println("The number entered by user: "+num);

  }
  public static void check(){


  try{
  num = scan.nextInt();


  }
  catch (Exception e){
  System.out.println("not a integer, try again");
  check();
  }

  }
}

Im new to coding, and am taking this summer to teach myself some basics. I was wondering if someone could advise me on how I can create this method to take in a int, and check the input to make sure thats its a int. If the input is not a int, I would like to re run in.

GBlodgett
  • 12,612
  • 4
  • 26
  • 42
some dude
  • 15
  • 4
  • [Validating input using java.util.Scanner](https://stackoverflow.com/q/3059333), [How do I keep a Scanner from throwing exceptions when the wrong type is entered?](https://stackoverflow.com/q/2496239), [How to use Scanner to accept only valid int as input](https://stackoverflow.com/q/2912817) – Pshemo Jul 14 '19 at 01:48

2 Answers2

0

Simple. Say you have something as shown below . . .

NumberThing.isNumber(myStringValue);

.isNumber() determines if your string is a numerical value (aka a number). As for putting the code in a loop to continue to ask the user for input if their input is invalid, using a while loop should work. Something like . . .

while (. . .) {
    // use something to exit the loop
    // depending on what the user does
}
0

You might consider moving the user request code to the check method. Also, use a break statement to exit your while loop after a valid number is entered.

while ( true )
{
    System.out.println( "Enter an integer."); 
    try
    {
        num = scan.nextInt();
        break; 
    }
    catch (Exception e)
    {
        System.out.println("not a integer"); 
    }
}
ManLaw
  • 115
  • 1
  • 9