gpt4 book ai didi

java - 从文件中读取

转载 作者:行者123 更新时间:2023-12-02 07:30:29 24 4
gpt4 key购买 nike

该程序有 2 个带有 main 方法的类,并且应该从文件中读取。我的问题是,double listPrice = fileScan.nextDouble(); 行给出了一个错误异常,例如 Exception in thread "main"java.util.InputMismatchException。错误在这个类中:

以下是文件内容:
本田雅阁

2004年16780.00 10.0

克莱斯勒SUV

2002年8600.00 0.0

丰田凯美瑞

2007年21799.99 3.0

福特福睿斯

2006年12345.78 5.5

//注意每行之间没有空格

class Proj1P2CarAryListService 
{

private ArrayList<Proj1CarData> carList = new ArrayList<Proj1CarData>();

public Proj1P2CarAryListService()
{
carList = new ArrayList<Proj1CarData>();
}

public void readStoreCarsData()
{


Scanner scan = new Scanner(System.in);

Scanner fileScan;
boolean validName = false;
double discountAmount;
double netPrice;

do
{

System.out.print("Enter file name: ");
String str1 = scan.nextLine();

try
{

fileScan = new Scanner(new File(str1));
validName = true;


while (fileScan.hasNext())

{

String name = fileScan.nextLine();
String modelYear = fileScan.next();
double listPrice = fileScan.nextDouble();
double percentDiscount = fileScan.nextDouble();

discountAmount = listPrice * percentDiscount/100.0;
netPrice = listPrice - discountAmount;

Proj1CarData proj1 = new Proj1CarData(name, modelYear, listPrice, percentDiscount, discountAmount, netPrice);
carList.add(proj1);
System.out.println(proj1.toString());

}// end while

}// end try

catch (FileNotFoundException fnfe)
{
System.out.println("Invalid File name; enter again");
}

} while (!validName);


}//readStoreCarsData

最佳答案

扫描器抛出此异常,表明检索到的 token 与预期类型的​​模式不匹配( double 必须用 . 或 分隔,就像 jlordo 所说的那样),或者 token 超出了预期类型的​​范围。也许是文件内容问题。

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

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