Java - 从文本文件中读取双精度

时间:2015-08-12 03:20:48

标签: java string double java.util.scanner

我正在尝试读取文件并确定该行中有多少个数字(以空格分隔)。如果有一个数字,则将该数字设置为圆的半径,并创建该半径的圆形对象。使用两个值(矩形)和三个值(三角形)执行类似的操作。

我认为我所遇到的错误是由于我的代码中存在问题,该问题从文本文件中获取数字,这些是字符串,并使用我的驱动程序类的第27行上的valueOf将它们转换为双精度数

我遇到的问题是当我运行驱动程序时出现以下错误:

Exception in thread "main" java.lang.NumberFormatException: For input string: "in7.txt"
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
    at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
    at java.lang.Double.parseDouble(Double.java:538)
    at java.lang.Double.valueOf(Double.java:502)
    at Assignment7.main(Assignment7.java:27)

这是我的驱动程序类:

import java.util.*;
import java.io.*;
public class Assignment7
{
   public static void main(String[] theArgs)
   {
      String filename = "in7.txt";
      int shapeNum;
      List<Double> shapeValues = new ArrayList<Double>();
      Shape myShape;
      double d;
      Scanner s = new Scanner(filename);
      try 
      {
         if (!s.hasNextLine())
         {
            throw new FileNotFoundException("No file was found!");
         }
         else
         {
            while (s.hasNextLine())
            {
               shapeNum = 0;
               Scanner s2 = new Scanner(s.nextLine());
               while (s2.hasNext())
               {
                  d = Double.valueOf(s2.next());
                  shapeNum++;
                  shapeValues.add(d);
               }
               if (shapeNum == 1)
               {
                  myShape = new Circle(shapeValues.get(0));
               }
               else if (shapeNum == 2)
               {
                  myShape = new Rectangle(shapeValues.get(0), 
                  shapeValues.get(1));
               }
               else
               {
                  myShape = new Triangle(shapeValues.get(0),
                  shapeValues.get(1), shapeValues.get(2));
               }
               shapeValues.clear();
               System.out.println(myShape);
            }
         }
         s.close();
      } 
      catch (FileNotFoundException e) 
      {
         System.out.println("File not found!" + e);
      }
   }
}

我一直在摆弄这段代码一小时,我无法让它正常运行。一些帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:3)

您应该将文件传递给扫描仪。 像这样

File filename = new File("in7.txt");
Scanner s = new Scanner(filename);

目前您传递的是字符串in7.txt,这就是您收到错误的原因

NumberFormatException: For input string: "in7.txt"
相关问题