3 回答

TA貢獻1735條經驗 獲得超5個贊
從您的文本示例中,分隔符不是用空格 ( " , "
) 包圍的逗號,而只是一個逗號 ( ","
)。刪除這些空格,你應該沒問題:
input.useDelimiter(",");

TA貢獻1862條經驗 獲得超7個贊
你得到InputMismatchException是因為最后一行input.nextInt()返回
"18
United States"
由于and之間沒有,分隔符(但有行分隔符),每個標記從分隔符返回到分隔符。18United States\n
您應該從文件中讀取所有行并按分隔符拆分它們:
List<String> lines = Files.readAllLines(Paths.get("Olympic.txt"));
for (String line : lines) {
String[] fields = line.split(",");
country.add(fields[0]);
name.add(fields[1]);
medals.add(Integer.valueOf(fields[2]));
}

TA貢獻1806條經驗 獲得超8個贊
請將您的代碼修改為:
public class Main {
public static void main(String[] args) throws FileNotFoundException {
ArrayList<String> country = new ArrayList<>();
ArrayList<String> name = new ArrayList<>();
ArrayList<Integer> medals = new ArrayList<>();
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader("F://test.txt"));
String line = reader.readLine();
while (line != null) {
String[] lineParts = line.split(",");
country.add(lineParts[0]);
name.add(lineParts[1]);
medals.add(Integer.valueOf(lineParts[2]));
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(country);
System.out.println(name);
System.out.println(medals);
}
}
在 test.xml 中:
Soviet Union,Larisa_LATYNINA,18
United States,Michael_PHELPS,16
Soviet Union,Nikolay_ANDRIANOV,15
代碼輸出:
[Soviet Union, United States, Soviet Union]
[Larisa_LATYNINA, Michael_PHELPS, Nikolay_ANDRIANOV]
[18, 16, 15]
添加回答
舉報