[英]Java String Parsing Error
嘿有人可以幫我解決我遇到的錯誤。 我正在從文件中取出幾行,並檢查它們是中低還是中。 如果字符串為空,我想讀取文件中的下一行。 我認為錯誤是當我將字符串解析為兩倍時。 這是我的代碼,對您有任何幫助! 首先這是我的錯誤
Exception in thread "main" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at BSCQueryManager.displayBar(BSCQueryManager.java:431)
at BSCQueryManager.main(BSCQueryManager.java:57)
這是我的代碼
String vMag;
String data;
double v;
int highCount = 0;
int medCount = 0;
int lowCount = 0;
// read file
File inFile = new File("bsc.dat");
Scanner starFile = new Scanner(inFile);
// while there is a vmag
while(starFile.hasNext()){
// read next line
data = starFile.nextLine();
data = data.substring(102, 107);
data.trim();
// if no vmag read next line
if(data.trim()!= ""){
v = Double.parseDouble(data);
// if vmag is > 6.0 add to countHigh
if (v > 6){
highCount++;
}
// if vmag is 5-6 add to countMed
if (v >= 5 && v <= 6){
medCount++;
}
// if vmag is < 5 add to countLow
if (v < 5){
lowCount++;
}
// end if
}
// end while
}
// display label
System.out.println(label);
System.out.println(highCount);
System.out.println(lowCount);
System.out.println(medCount);
嘗試更換:
data.trim();
// if no vmag read next line
if(data.trim()!= ""){
與
data = data.trim();
// if no vmag read next line
if(data.length > 0){
字符串之一為空:
class Test1 {
public static void main(String[] args) {
Double.parseDouble("");
}
}
產生:
C:\Temp>java Test1
Exception in thread "main" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:992)
at java.lang.Double.parseDouble(Double.java:510)
at Test1.main(Test1.java:3)
數據字符串絕對不能解析為雙精度。 可能為空(您的字符串非空邏輯有缺陷,請嘗試
data.isEmpty()
而是該值可能是其他無法解析的值,例如字母或單詞。
您可以嘗試調試,或捕獲異常並打印數據值。
try{
Double.parseDouble(data);
}catch(NumberFormatException e){
throw new RuntimeException(data + " is not a number");
}
這將使您看到出了什么問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.