gpt4 book ai didi

java - 未知 "NumberFormatting"问题

转载 作者:行者123 更新时间:2023-11-30 06:03:14 25 4
gpt4 key购买 nike

(提前,抱歉这篇冗长且有点小众的文章,但我被困住了)这里是完整的 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)`

我的问题是为什么会发生这种情况,我该如何解决它?或者我该如何捕获不会破坏代码的异常?

(另外,如果有人能告诉我为什么我的代码不会分行,那就太棒了)

谢谢!!

最佳答案

根据错误消息,这是文本文件中的字符串格式,因此下面的代码根据空格分隔符分割行,并通过删除所有额外字符来过滤值

注意:如果文本文件中的每条记录都是采用此格式的单独行,则此代码有效

String s ="1946: It's a Wonderful Life ($14.95)";
String[] ar = s.split(" ");
System.out.println(ar[0].substring(0, ar[0].length()-1));
String str = String.join("," ,Arrays.copyOfRange(ar, 1, ar.length-2)).replaceAll(",", " ");
System.out.println(str);
System.out.println(ar[ar.length-1].substring(2, ar[ar.length-1].length()-1));

输出:

1946
It's a Wonderful
14.95

关于java - 未知 "NumberFormatting"问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51853778/

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