Domanda

I am getting a NumberFormatException in talend ETL tool for the following statement:

Integer.parseInt("+2");

Error details:

Exception in component tJavaRow_3
java.lang.NumberFormatException: For input string: "+2"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:449)
at java.lang.Integer.parseInt(Integer.java:499)

Which is really a simple code that runs without any issue in my test java program.

public class Main { 
   public static void main(String[] args) { 
      String s = "+000000100"; 
      System.out.println(String.valueOf(new Integer(s))); 
   } 
}

Actually am getting this value from a positional file and the value can be something like +0002 or -0002 (Some valid number prefixed with sign). And one thing is sure there will not be any decimals in the input.

Thanks in advance.

È stato utile?

Soluzione

In your context +2 must mean a positive number 2. Watch out when passing strings to the function that does the parsing, because since it parses ints some expressions such as 3.5 or 3,5 (decimals) will not result like expected. Double.parseDouble or Float.parseFloat should be used in those cases instead if you have control over that code. On the other hand, negative numbers like -2 will be parsed withour any problem.

EDIT: If you're using positional files just remove the + from the beginning of your string either by using a regular expression or obtaining a substring. You can, also, use startsWith("+") to check if the string starts with +.

Altri suggerimenti

+2 is not a valid intefer. It should be just 2.

Just zap the + from the start of the number:

num = num.replaceAll("\\+", "");
// parse, etc.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top