I'm wondering how to do something only if Integer.parseInt(whatever) doesn't fail.
More specifically I have a jTextArea of user specified values seperated by line breaks.
I want to check each line to see if can be converted to an int.
Figured something like this, but it doesn't work:
for(int i = 0; i < worlds.jTextArea1.getLineCount(); i++){ if(Integer.parseInt(worlds.jTextArea1.getText(worlds.jTextArea1.getLineStartOffset(i),worlds.jTextArea1.getLineEndOffset(i)) != (null))){} }
Any help appreciated.
We have used the parseInt method of the Integer class before. The method throws a NumberFormatException if the string it has been given cannot be parsed into an integer. The above program throws an error if the user input is not a valid number. The exception will cause the program execution to stop.
ParseInt can lead to complex problems—it throws a NumberFormatException on invalid data. Many exceptions will lead to slower program performance.
You can call the Number. isNaN function to determine if the result of parseInt is NaN . If NaN is passed on to arithmetic operations, the operation result will also be NaN .
Return ValueparseInt(String s) − This returns an integer (decimal only). parseInt(int i) − This returns an integer, given a string representation of decimal, binary, octal, or hexadecimal (radix equals 10, 2, 8, or 16 respectively) numbers as input.
Check if it is integer parseable
public boolean isInteger(String string) { try { Integer.valueOf(string); return true; } catch (NumberFormatException e) { return false; } }
or use Scanner
Scanner scanner = new Scanner("Test string: 12.3 dog 12345 cat 1.2E-3"); while (scanner.hasNext()) { if (scanner.hasNextDouble()) { Double doubleValue = scanner.nextDouble(); } else { String stringValue = scanner.next(); } }
or use Regular Expression like
private static Pattern doublePattern = Pattern.compile("-?\\d+(\\.\\d*)?"); public boolean isDouble(String string) { return doublePattern.matcher(string).matches(); }
public static boolean isParsable(String input) { try { Integer.parseInt(input); return true; } catch (final NumberFormatException e) { return false; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With