我目前正在用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();
但想不通爲什麼這些語句不工作。
那麼輸入文件只能被讀作字符串(實際上是)? – ke1v3y 2014-11-23 22:23:04
將線條閱讀和其他閱讀相結合並不是一個好主意。 – 2014-11-23 22:24:23
感謝您的提示。您的解決方案奏效 – ke1v3y 2014-11-23 22:27:47