[英]How can I split a String into a String array for each character, while grouping a “minus” sign with the integer that follows it?
[英]Can't change String to Integer because negative sign follows number
我正在使用Java讀取CSV文件並使用給定的項目進行一些數據分析。 我讀到的幾個數據點是一堆不同的數字,范圍從-999到999。我想將這些數字相互比較,因此首先將String轉換為Integer。 我得到的問題是CSV文件使用數字(1-)后面的負號保存了負數。 這將引發NullFormatException。 我覺得有一個簡單的方法可以解決我所忽略的問題。 任何幫助都會很棒。
假設隨機數據為{1,19-,20-,7,8}我需要{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]);
}
您可以使用DecimalFormat以自定義格式解析整數:
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());
}
}
輸出:
-123
321
嘗試這樣的事情。 它將在末尾檢測連字符,並在解析數字之前將其刪除,並將其設置為負值。
private int parseInt(String str) {
if (str.endsWith("-")) {
str = str.substring(0, str.length() - 1);
return -Integer.parseInt(str);
} else {
return Integer.parseInt(str);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.