gpt4 book ai didi

java - 主线程中的异常 - java.util.InputMismatchException

转载 作者:搜寻专家 更新时间:2023-10-31 20:18:26 25 4
gpt4 key购买 nike

我一直在阅读 Java for the Dummies,我遇到了这个错误:

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)
at TeamFrame.<init>(TeamFrame.java:18)
at ShowTeamFrame.main(ShowTeamFrame.java:7)

这是代码:

import java.text.DecimalFormat;

public class Player {
private String name;
private double average;

public Player(String name, double average) {
this.name=name;
this.average=average;
}

public String getName() {
return name;
}

public double getAverage() {
return average;
}

public String getAverageString() {
DecimalFormat decFormat = new DecimalFormat();
decFormat.setMaximumIntegerDigits(0);
decFormat.setMaximumFractionDigits(3);
decFormat.setMinimumFractionDigits(3);
return decFormat.format(average);
}
}


import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.GridLayout;

@SuppressWarnings("serial")
public class TeamFrame extends JFrame {

public TeamFrame() throws IOException {
Player player;
Scanner hankeesData =
new Scanner(new File("d:/eclipse/Workplace/10-02 book/Hankees.txt"));

for (int num = 1; num <= 9; num++) {
player = new Player(hankeesData.nextLine(),
hankeesData.nextDouble());
hankeesData.nextLine();

addPlayerInfo(player);
}

setTitle("The Hankees");
setLayout(new GridLayout(9, 2, 20, 3));
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);

hankeesData.close();
}

void addPlayerInfo(Player player) {
add(new JLabel(" " + player.getName()));
add(new JLabel(player.getAverageString()));
}
}

import java.io.IOException;

class ShowTeamFrame {

public static void main(String args[])
throws IOException {
new TeamFrame();
}
}

这是 .txt 文件:

Barry Burd
.101
Harriet Ritter
.200
Weelie J. Katz
.030
Harry "The Crazyman" Spoonswagler
.124
Filicia "Fishy" Katz
.075
Mia, Just "Mia"
.111
Jeremy Flooflong Jones
.102
I. M. D'Arthur
.001
Hugh R. DaReader
.212

直接从书的网站上截取的,所以我认为一定没有错误。

最佳答案

在创建 hankeesData 后将其插入您的代码中:

hankeesData.useLocale(java.util.Locale.ENGLISH);

我注意到你的程序在“.”的情况下运行。替换为“,”,新代码现在告诉 Scanner 使用英语方法。

更新:如果您在最后一行收到 NoSuchElementException: No line found,那是因为您的最后一行没有\n。使用 hasNextLine(),如 HyperZ 答案末尾所示。

关于java - 主线程中的异常 - java.util.InputMismatchException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32181384/

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