我目前正在用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();
但无法弄清楚这些陈述为什么不起作用。
答案 0 :(得分:0)
当你致电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
答案 1 :(得分:0)
您的主要问题是您没有设置正确的分隔符。初始化扫描程序后,执行inputFile.useDelimiter("\n")
将分隔符设置为换行符 - 默认为空格。
然后,您可以使用inputFile.next()
读取字符串,使用inputFile.nextInt()
读取int,不会有任何问题。