【发布时间】:2015-08-12 03:20:48
【问题描述】:
我正在尝试通读一个文件并确定该行中有多少个数字(以空格分隔)。如果有一个数字,则将该数字设置为圆的半径,并创建该半径的圆对象。对两个值(一个矩形)和三个值(一个三角形)进行类似的操作。
我相信我遇到的错误是因为我的代码出现问题,该代码从文本文件中获取数字,这些数字是字符串,并在我的驱动程序类的第 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);
}
}
}
我一直在摆弄这段代码一个小时,但我无法让它正确运行。一些帮助将不胜感激。谢谢!
【问题讨论】:
-
new Scanner() 没有文件名。您只是将文件名作为字符串处理,而不是文件的内容。
标签: java string double java.util.scanner