【发布时间】:2021-11-20 01:50:46
【问题描述】:
我想弄清楚为什么我的文件不会输出。它是一个数据文件,包括显示器及其刷新率、响应时间、显示器型号和品牌。每当我运行它时,我都会遇到 at.util.Scanner 错误和 com.company.MonitorsTest.loadMonitors 错误。数据文件的设置方式好吗?
class Monitors{
public String brandName;
public int modelNumber;
public int refreshRate;
public int responseTime;
}
public class MonitorsTest {
public static void main(String[] args) {
Monitors[] gaming = new Monitors[100];
int dataFile;
int choice;
System.out.println("\nDisplay Monitors\n");
System.out.println(" Enter one of the following commands:");
System.out.println("(1)- Display the entire data file ");
System.out.println("(2) - Display certain information on a monitor");
System.out.println("(3) - Display a histogram");
Scanner keyboard = new Scanner(System.in);
System.out.println();
System.out.println("Enter 1, 2, or 3 ");
choice = keyboard.nextInt();
dataFile = (loadMonitors(gaming));
while ( choice != 3){
if (choice < 1 || choice > 3) {
System.out.println("Enter 1, 2, 3 ");
choice = keyboard.nextInt();
}
else if (choice == 1){
System.out.println(dataFile);
}
}
}
private static int loadMonitors(Monitors[] gaming) {
int nMonitors = 0;
try {
File file = new File("C:\\Users\\kento\\IdeaProjects\\Program3\\src\\monitors.txt");
Scanner scan = new Scanner(file);
do {
gaming[nMonitors] = new Monitors();
gaming[nMonitors].brandName = scan.next();// Error here
gaming[nMonitors].modelNumber = scan.next();// Error here
gaming[nMonitors].responseTime = scan.nextDouble();
gaming[nMonitors].refreshRate = scan.nextInt();// Error here
++nMonitors;
}
while (gaming[nMonitors - 1].refreshRate != 0);
--nMonitors;
}
catch (IOException ioe){
System.out.println(" File access error" + ioe);
nMonitors = 0;
}
return nMonitors;
}
错误列表:
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.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at com.company.MonitorsTest.loadMonitors(MonitorsTest.java:62)
at com.company.MonitorsTest.main(MonitorsTest.java:39)
文本文件
Sceptre DCIP3 1 165
AOC C24G1A 1 165
ASUS VG278QR 05 144
Sceptre E22 5 75
Alienware AW2521HF 1 240
【问题讨论】:
-
你能发布你得到的错误的全文吗?并且还在源代码中添加注释,告诉我们错误来自哪几行。
-
第 62 行和第 39 行分别是哪几行?
-
39 是 dataFile = (loadMonitors(gaming)); 62 是 Size=scan.nextInt();
-
显然“大小”不是您数据文件中的整数。您能否告诉我们这个错误发生在哪个索引上(即
nMonitors的值,到目前为止您读取了多少个监视器),并在数据文件中向我们显示该条目,以便我们查看。 -
请注意
nextInt会在缓冲区中留下一个悬空的新行字符,随后的nextInt调用将无法理解