2012-11-05 33 views
0

尝试从具有不同内容的文件读取双精度数据。例如,如果它是一个double,那么该消息应该是“Double number is 23.5”。如果不是双数,则该消息应该是“六十三不是双数”。文件内容是打开文件并读取双精度数据

97.9

100.1

63个

12.4

3002.4

34.6

这是它

............

我写的代码打开文件和扫描下一个行但似乎没有正常工作。

class ReadDouble 
{ 

Scanner scan = new Scanner(System.in); 


try 

{ 

    File textFile = new File ("doubleData.txt"); 
    Scanner scanFile = new Scanner (textFile); 
    String str = scan.nextLine(); 

    while(scanFile.hasNextLine()) 
    { 

     double num = Double.parseDouble(str); 
     if(str == num) 
     { 
      System.out.println("Double number is" + str); 
     } 

    }//end while 


}//end try 

catch (NumberFormatException nfe) 
{ 
    System.out.println(str + "Is not a Double number"); 
} 

}

} //结束类

+3

'scan.nextLine()'应该在你的while循环中,否则你不会经过第一行。 – Charlie

回答

0

首先,您应该在循环中调用String str = scan.nextLine();,否则您只会阅读第一行。此外,您的try/catch区块应在while循环内围绕double num = Double.parseDouble(str);缠绕,否则在遇到您的第一个非双倍区域后,您不会再拨打scan.nextLine()

最后,你不应该这样做if(str == num),因为这将永远是错误的。如果Double.parseDouble(str)不会引发异常,则它包含在该行上找到的double。

这里是一个解决方案,从标准中:

import java.util.Scanner; 

public class ReadDouble { 

    public static void main(String[] args){ 
     Scanner scan = new Scanner (System.in); 

     while(scan.hasNextLine()){ 
     String str = scan.nextLine(); 

     try { 
      num = Double.parseDouble(str); 
      System.out.println("Double number is " + num); 
     } catch (NumberFormatException nfe) { 
      System.out.println(str + " is not a Double number"); 
     }  
    } 
} 
} 

另一种选择是使用Scanner,看看下一个元素是double如果使用nextDouble()使用nextLine()否则读读它。

+0

它只在输入内容时才起作用,但它不会读取整个文件。 wile(scan.nextLine)循环里面try catch会给我文件中的所有内容吗? – Nic

+0

这个例子只有当你输入一些东西时才起作用,因为我的'Scanner'的输入是'System.in'。您需要将输入更改为您想要阅读的文件。 – Joe

+0

完全忘记了文件0)) – Nic

2

你的try-catch应该是while循环里面,否则它会出来的线的第一个例外,其余的将被忽略。

+0

有道理,因为它给了用户另一个输入正确信息的机会。 – Nic

0

鉴于您的文件格式,我不会打扰扫描仪。只要读取每一行,将它传递给Double.valueOf(String),如果它不是double,则会捕获该异常。