简体   繁体   中英

Getting NumberFormat while trying to parse a string

I'm trying to parse a string to an integer. The string is a number when I do sys out but when I try to parse it then it adds a double quote at the beginning. I'm not doing anything additional.

Following is a snippet of my code:

System.out.println("Result 2 is: "+results[2]);
String temp = results[2].replace("\"", "");
System.out.println("String Temp is: "+temp);
int height = Integer.parseInt(results[1].replace("\"", ""));
int width = Integer.parseInt(results[2].replace("\"", ""));

In the logs:

String Temp is: 2550
wt.system.err wcadmin - java.lang.NumberFormatException: For input string: "2550

This exception is only for result[2]. Something to do with character set?

Option 1: Parse temp . Change

int width = Integer.parseInt(results[2].replace("\"", ""));

to

int width = Integer.parseInt(temp);

Option 2: Use a regular expression to remove everything not a digit instead of trying to handle corner cases by hand.

int width = Integer.parseInt(results[2].replaceAll("\\D+", ""));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM