[英]Java String Parsing Error
Hey can someone help me with my error i am getting. 嘿有人可以帮我解决我遇到的错误。 I am taking apart lines out of my file and check wether they are low med or high. 我正在从文件中取出几行,并检查它们是中低还是中。 If the string is blank i want to read the next line in the file. 如果字符串为空,我想读取文件中的下一行。 I think the error is when i am parsing the sting to a double. 我认为错误是当我将字符串解析为两倍时。 Heres my code any help is appriciated! 这是我的代码,对您有任何帮助! First here is my 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)
Here is my code 这是我的代码
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);
Try replacing: 尝试更换:
data.trim();
// if no vmag read next line
if(data.trim()!= ""){
with 与
data = data.trim();
// if no vmag read next line
if(data.length > 0){
One of the strings is empty: 字符串之一为空:
class Test1 {
public static void main(String[] args) {
Double.parseDouble("");
}
}
produces: 产生:
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)
The data string definitely isn't parsable to a double. 数据字符串绝对不能解析为双精度。 It may be blank (your string not empty logic is flawed, try 可能为空(您的字符串非空逻辑有缺陷,请尝试
data.isEmpty()
instead) or the value could be something else unparseable eg a letter or word. 而是该值可能是其他无法解析的值,例如字母或单词。
You could try debugging, or catching the exception and printing the value of data. 您可以尝试调试,或捕获异常并打印数据值。
try{
Double.parseDouble(data);
}catch(NumberFormatException e){
throw new RuntimeException(data + " is not a number");
}
That will let you see what's going wrong. 这将使您看到出了什么问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.