-2

I Have an JOptionPane that I want to convert to integer, but only if it actually is an integer the user inserts. How do I do this? if-statement?

Habbo
  • 155
  • 1
  • 8

2 Answers2

0

You can just parse and catch the exception:

    Integer value;
    try{
        value = Integer.valueOf(input);
    } catch(NumberFormatException ignored) {
        value = 0;
    }

Alternatively you can use a regular expression:

    Integer value;
    if (input.matches("\\d+")) {
        value = Integer.valueOf(input);
    } else {
        value = 0;
    }
Amila
  • 5,195
  • 1
  • 27
  • 46
0
try{
    Integer number;
    Scanner scanner=new Scanner(System.in);
    System.out. println("your input");
    if(scanner. hasNextInt())
    {
        Integer number=scanner. nextInt();
        System.out. println(number);
     }
 }
catch(NumberFormatExceptoion nfe)
{
    number=0;
}
UmNyobe
  • 22,539
  • 9
  • 61
  • 90
Madhav Sharma
  • 31
  • 1
  • 4