簡體   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