Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - checking if parseInt throws exception

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.

like image 819
Mike Haye Avatar asked Jun 23 '11 15:06

Mike Haye


People also ask

Can parseInt throw an exception in Java?

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.

Can parseInt produce exception?

ParseInt can lead to complex problems—it throws a NumberFormatException on invalid data. Many exceptions will lead to slower program performance.

How do I know if my parseInt is NaN?

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 .

How do you handle integer parseInt?

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.


2 Answers

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(); } 
like image 45
Kerem Baydoğan Avatar answered Sep 22 '22 17:09

Kerem Baydoğan


public static boolean isParsable(String input) {     try {         Integer.parseInt(input);         return true;     } catch (final NumberFormatException e) {         return false;     } } 
like image 153
fmucar Avatar answered Sep 19 '22 17:09

fmucar