gpt4 book ai didi

java - 从输入文件读取整数数组

转载 作者:太空宇宙 更新时间:2023-11-04 14:21:49 25 4
gpt4 key购买 nike

我目前正在用 Java 编写一个项目,该项目将获取输入文件并将其读入多个并行数组。有几个限制——我们不能使用数组列表,必须使用 Scanner 读取文件。将其读入数组后,我还需要编写一些其他步骤,但我遇到了挂断。

    public static void main(String[] args) throws FileNotFoundException {

final int ARRAY_SIZE = 10;
int choice;
int i, variableNumber;
String[] customerName = new String[ARRAY_SIZE];
int[] customerID = new int[ARRAY_SIZE];
String[] os = new String[ARRAY_SIZE];
String[] typeOfProblem = new String[ARRAY_SIZE];
int[] turnAroundTime = new int[ARRAY_SIZE];

readFile(customerName, customerID, os, typeOfProblem, turnAroundTime);

}

public static void readFile(String[] customerName, int[] customerID, String[] os, String[] typeOfProblem, int[] turnAroundTime) throws FileNotFoundException
{
File hotlist = new File("hotlist.txt");
int i = 0;

if (!hotlist.exists())
{
System.out.println("The input file was not found.");
System.exit(0);
}
Scanner inputFile = new Scanner(hotlist);
while (inputFile.hasNext())
{
customerName[i] = inputFile.nextLine();
System.out.println(customerName[i]);
customerID[i] = inputFile.nextInt();
os[i] = inputFile.nextLine();
typeOfProblem[i] = inputFile.nextLine();
turnAroundTime[i] = inputFile.nextInt();
i++;
}
System.out.println("This is only a test." + customerName[1] + "\n" + customerID[1] + "\n"
+ os[1] + "\n" + typeOfProblem[1] + "\n" + turnAroundTime[1]);
}

当我尝试运行上述代码时,它失败并出现以下错误:

run:
Mike Rowe
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 mckelvey_project3.McKelvey_Project3.readFile(McKelvey_Project3.java:70)
at mckelvey_project3.McKelvey_Project3.main(McKelvey_Project3.java:33)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

hotlist.txt文件内容如下:

Mike Rowe
1
Windows DOS
Too Much ASCII Porn
3
Some Guy
2
Windows 10
Too Much Windows
200

非常感谢任何帮助!顺便说一句,所有 System.out 语句都是测试语句,因为我试图调试我的代码。我已将错误具体隔离

customerID[i] = inputFile.nextInt();

类似

turnAroundTime[i] = inputFile.nextInt();

但无法弄清楚为什么这些语句不起作用。

最佳答案

当您调用Scanner.nextInt()时它只消耗int,并在那里留下任何尾随空格或换行符。相反,你可以使用类似的东西,

Scanner inputFile = new Scanner(hotlist);
while (inputFile.hasNext()) {
customerName[i] = inputFile.nextLine();
System.out.println(customerName[i]);
String custId = inputFile.nextLine();
customerID[i] = Integer.parseInt(custId);
os[i] = inputFile.nextLine();
typeOfProblem[i] = inputFile.nextLine();
String turnAround = inputFile.nextLine();
turnAroundTime[i] = Integer.parseInt(turnAround);
i++;
}

我得到(用你的代码/文件),

Mike Rowe
Some Guy
This is only a test.Some Guy
2
Windows 10
Too Much Windows
200

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

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