我正在寫一個程序,通過讀取各種類型的數據的文件。我試圖將文件中的數據傳遞給我創建的各種數組。從文件InputMismatchException當使用輸入掃描器
樣品部分(雙倍行距換行第一/姓氏和國家之間。之間類別標籤的空格,但空格是空格)
Name Age Country Year Closing Date Sport Gold Silver Bronze Total
Joe Max 24 Algeria 2012 8/12/2012 Athletics 1 0 0 1
Tom Lan 27 United States 2008 8/24/2008 Rowing 0 1 0 1
當我的代碼編譯,但是,我得到InputMismatchException。我想知道它是否處理在每行結尾處沒有標籤的事實。任何人都可以幫助我通過這個?
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
intro();
Scanner input1 = null;
Scanner input2 = null;
int lineCount = 0;
try {
input1 = new Scanner(new File("olympicstest.txt"));
}
catch (FileNotFoundException e) {
System.out.println("Invalid Option");
System.exit(1);
}
while (input1.hasNextLine()) {
lineCount++;
input1.nextLine();
}
lineCount = lineCount - 1;
String[] country = new String[lineCount];
int[] totalMedals = new int[lineCount];
String[] name = new String[lineCount];
int[] age = new int[lineCount];
int[] year = new int[lineCount];
String[] sport = new String[lineCount];
try {
input2 = new Scanner(new File("olympicstest.txt"));
input2.useDelimiter("\t");
}
catch (FileNotFoundException e) {
System.out.println("Invalid Option"); // not sure if this line is needed
System.exit(1); // not sure if this line is needed
}
String lineDiscard = input2.nextLine();
for (int i = 0; i < lineCount; i++) {
name[i] = input2.next();
age[i] = input2.nextInt();
country[i] = input2.next();
year[i] = input2.nextInt();
input2.next(); // closing ceremony date
sport[i] = input2.next();
input2.nextInt(); // gold medals
input2.nextInt(); // silver medals
input2.nextInt(); // bronze medals
totalMedals[i] = input2.nextInt();
}
}
你說這是你的輸出,你不是這個意思嗎? –
你是對的。它應該讀取輸入。現在解決。 – Rivers31334