gpt4 book ai didi

java - 使用扫描仪从文件中读取 double 值,java.util.InputMismatchException

转载 作者:太空宇宙 更新时间:2023-11-04 11:52:28 24 4
gpt4 key购买 nike

大家好,我是 Java 初学者,我试图从文件中读取一些数据,但是当它尝试读取 double 值时发生错误,我不明白为什么。这是我的代码:

package bestcombo;
import java.io.*;
import java.util.Scanner;
public class Componentes
{
String name = "";
Lojas[] stores = new Lojas[8];
public void ComponenteNome(String nome)
{
name = nome;
}
public void InicializeStores()
{
for (int i = 0; i < 8; i++)
{
stores[i] = new Lojas();
}
}
public void InserirInformacao() throws IOException
{
int i = 0, val = 0, quant = 0;
double price = 0;
String FileName = "";
Scanner ReadKeyboard = new Scanner(System.in), ReadFile = null;
InicializeStores();
System.out.println("File:\n");
FileName = ReadKeyboard.nextLine();
ReadFile = new Scanner(new File(FileName));
while(ReadFile.hasNext())
{
ReadFile.useDelimiter(":");
val = ReadFile.nextInt();
ReadFile.useDelimiter(":");
price = ReadFile.nextDouble();
ReadFile.useDelimiter("\\n");
quant = ReadFile.nextInt();
stores[i].LojaValor(val);
stores[i].LojaQuantidade(quant);
stores[i].LojaPreco(price);
}
}
}

这是我文件中的数据:

1:206.90:1
2:209.90:1
3:212.90:1
4:212.90:1
5:213.90:1
6:224.90:1
7:229.24:1
8:219.00:1

这是错误

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
at bestcombo.Componentes.InserirInformacao(Componentes.java:34)
at bestcombo.BestCombo.main(BestCombo.java:13)

最佳答案

从文件读取时,我建议使用 getNextLine(),它可以使代码和值提取变得更加简单。另外,您读入的数据文件是用冒号分隔的,这使得提取值变得非常容易。尝试使用这个 while 循环来代替

while(ReadFile.hasNextLine())
{
String inputOfFile = ReadFile.nextLine();
String[] info = inputOfFile.split(":");
try{
if(info.length == 3)
{
val = Integer.parseInt(info[0]);
price = Double.parseDouble(info[1]);
quant = Integer.parseInt(info[2]);
stores[i].LojaValor(val);
stores[i].LojaQuantidade(quant);
stores[i].LojaPreco(price);
i++;
}
else
{
System.err.println("Input incorrectly formatted: " + inputOfFile);
}
}catch (NumberFormatException e) {
System.err.println("Error when trying to parse: " + inputOfFile);
}
}

我的猜测是您正在读取的文件中有一个额外的换行符或其他内容。上面应该能够很容易地处理你的文件。此实现的另一个优点是,即使您遇到文件中数据格式不正确的位置,它也会继续从文件中读取。

关于java - 使用扫描仪从文件中读取 double 值,java.util.InputMismatchException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41681907/

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