Reputation: 80
I am using Java to read in a CSV file and do some data analysis with the items given. A couple of the data points that I read in are a bunch of different numbers that can range from -999 to 999. I want to compare these numbers to each other so I start by turning the String into an Integer. The problem I get is that the CSV file saves negative numbers with the negative sign following the number (1-). This throws a NullFormatException. I feel like there is an easy way around this that I'm overlooking. Any help would be great.
Say random data is {1,19-,20-,7,8} I need {1,-19,-20,7,8}
int[] nnaOH = new int[x];
int[] nwOH = new int[x];
int[] nuaOH = new int[x];
for (int z = 1; z < x; z++){
nnaOH[z] = Integer.parseInt(naOH[z]);
nwOH[z] = Integer.parseInt(wOH[z]);
nuaOH[z] = Integer.parseInt(uaOH[z]);
}
Upvotes: 0
Views: 80
Reputation: 1982
You can use DecimalFormat to parse your integers with a custom format:
import java.text.DecimalFormat;
import java.text.ParseException;
public class DecimalFormatTest {
public static void main(String[] args) throws ParseException {
DecimalFormat decimalFormat = new DecimalFormat("#;#-");
System.out.println(decimalFormat.parse("123-").intValue());
System.out.println(decimalFormat.parse("321").intValue());
}
}
Output:
-123
321
Upvotes: 2
Reputation: 2410
Try something like this. It will detect the hyphen at the end and remove it before parsing the number, setting it to a negative value.
private int parseInt(String str) {
if (str.endsWith("-")) {
str = str.substring(0, str.length() - 1);
return -Integer.parseInt(str);
} else {
return Integer.parseInt(str);
}
}
Upvotes: 0