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?
Asked
Active
Viewed 108 times
2 Answers
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,125
- 1
- 26
- 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
- 21,924
- 8
- 55
- 89
Madhav Sharma
- 31
- 1
- 4