日期:2014-05-20  浏览次数:21003 次

循环的不同结果
以下代码注释掉的部分去掉注释后就会出现以下错误,红色字体部分标明出现了空串,而Double.parseDouble的参数不能为空串。
Exception in thread "main" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:994)
at java.lang.Double.parseDouble(Double.java:510)
at javaapplication10.JavaApplication10.main(JavaApplication10.java:34)
Java Result: 1

debug后发现去掉注释后while循环判断没成功,row为空的时候仍然进入了while循环,导致str1为空串求高人指点
Java code

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication10;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Administrator
 */
public class JavaApplication10 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
         String row;
        FileReader read;
        try {
            read = new FileReader("D:/data.txt");   
            BufferedReader br = new BufferedReader(read); 
            try {
                while ((row = br.readLine()) != null) {
                       String str1[] = row.split(" ");
//                      for (String stemp : str1) {
//                   double h = Double.parseDouble(stemp);
//                        }
                }
            } catch (IOException ex) {
                Logger.getLogger(JavaApplication10.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(JavaApplication10.class.getName()).log(Level.SEVERE, null, ex);
        }
         
       
          
       
      
    }
}




------解决方案--------------------
把文件d:/data.txt空行删掉试试。

------解决方案--------------------
顶一楼:应该是由于data.txt里面有空串而出现的异常。可采取的办法有如下:
1.删除所有的data.txt里面的空行
2.修改for循环如下:
Java code

                                       for (String stemp : str1) {
                        if (stemp.equals("")) {
                            continue;
                        }
                        double h = Double.parseDouble(stemp);
                        System.out.println(h);
                    }

------解决方案--------------------
Java code
for (int i = 0; i < 3; i++)