-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?

0

2 Answers 2

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;
    }
Sign up to request clarification or add additional context in comments.

Comments

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;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.