gpt4 book ai didi

Java - 从文本文件中读取 double 值

转载 作者:行者123 更新时间:2023-11-29 05:01:35 25 4
gpt4 key购买 nike

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

我认为我收到的错误是因为我的代码有问题,该代码从文本文件中获取数字(字符串),并使用 valueOf 在第 27 行将它们转换为 double 值我的司机类。

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

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"

关于Java - 从文本文件中读取 double 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31955482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com