【发布时间】:2019-01-22 00:57:56
【问题描述】:
(提前,很抱歉这篇冗长且有点小众的帖子,但我非常卡住)在这里完成 Java 编程新手,我一直在关注“Java ALL-IN-ONE for Dummies”一书,并且我遇到了一个我似乎无法克服的障碍。出于某种原因,我的代码以及从本书下载网站获取的代码都会引发 NumberFormatException。我的代码如下..
`package videoRead;
import java.io.*;
import java.text.NumberFormat;
public class reader
{
public static void main(String[] args)
{
NumberFormat cf = NumberFormat.getCurrencyInstance();
BufferedReader in = getReader("Movie.txt");
Movie movie = readMovie(in);
while (movie != null)
{
String msg = Integer.toString(movie.year);
msg += ": " + movie.title;
msg += " (" + cf.format(movie.price) + ")";
System.out.print(msg);
movie = readMovie(in);
}
}
private static BufferedReader getReader(String name)
{
BufferedReader in = null;
try
{
File file = new File(name);
in = new BufferedReader(
new FileReader("C:\\Users\\hunte\\Desktop\\Movie.txt") );
}
catch (FileNotFoundException e)
{
System.out.print(
"the file doesn't exist.");
System.exit(0);
}
return in;
}
private static Movie readMovie(BufferedReader in)
{
String title;
int year;
double price;
String line = "";
String[] data;
try
{
line = in.readLine();
}
catch (IOException e)
{
System.out.print("I/O Error");
System.exit(0);
}
if (line == null)
return null;
else
{
data = line.split("\t");
title = data[0];
year = Integer.parseInt(data[1]);
price = Double.parseDouble(data[2]);
return new Movie(title, year, price);
}
}
private static class Movie
{
public String title;
public int year;
public double price;
public Movie(String title, int year, double price)
{
this.title = title;
this.year = year;
this.price = price;
}
}
}
错误代码为
`1946: It's a Wonderful Life ($14.95)1972: Young Frankenstein ($16.95)1973: Star Wars ($17.95)1987: The Princess Bride ($14.95)1989: Glory ($14.95)Exception in thread "main" java.lang.NumberFormatException: For input string: "14.95"
at java.base/java.lang.NumberFormatException.forInputString(Unknown Source)
at java.base/java.lang.Integer.parseInt(Unknown Source)
at java.base/java.lang.Integer.parseInt(Unknown Source)
at videoRead/videoRead.reader.readMovie(reader.java:65)
at videoRead/videoRead.reader.main(reader.java:20)`
我的问题是为什么会发生这种情况,我该如何解决?或者我该如何捕捉不会破坏代码的异常?
(另外,如果有人能告诉我为什么我的代码不会分行,那也太棒了)
谢谢!!
【问题讨论】:
-
它说
"14.95"不能被解析为整数。您是否可能在预计一年的地方有错误的货币价值?那将在文件中 -
这是因为双值中的$符号
-
那里出了点问题。
1946: It's a Wonderful Life ($14.95)与\t拆分可能会给出1946:、It's a Wonderful Life和($14.95),分别为title、year和price(假设它是冒号后面的制表符。我怀疑那里只有一个tab,冒号后面没有tab。 -
您的代码有几个问题,正如已经指出的那样:假设您的文件可以正确拆分,您会尝试将标题 (
data[1]) 解析为 int 并且这是绑定的失败。即使您使用正确的data[0],您也会尝试解析1946:,由于尾随:,它也会失败。此外,您会尝试将($14.95)解析为双精度,并且由于($...)它也会失败。因此:首先从行数据中提取正确的部分,然后尝试解析这些部分。 -
可以发布你的txt文件数据吗?
标签: java string exception-handling number-formatting