繁体   English   中英

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

[英]Java - Reading A Double From A Text File

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

我相信我遇到的错误是由于我的代码存在问题而引起的,该代码从文本文件中获取数字,这些数字是字符串,并使用驱动程序类的第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);
      }
   }
}

我已经摆弄了一个小时的代码,但无法正常运行。 一些帮助将不胜感激。 谢谢!

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

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

当前您正在传递一个字符串in7.txt ,这就是为什么您会收到错误消息

NumberFormatException: For input string: "in7.txt"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM