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]
添加回答
举报