简体   繁体   English

将玩家列表写入文件时出现 IndexOutOfBoundsException

[英]IndexOutOfBoundsException when writing a list of players to a file

I'm working on assignment for OOP and am stuck on the last step which is, "Write all players to an output file that has a similar format of the input file."我正在为 OOP 分配工作,并坚持最后一步,即“将所有玩家写入具有类似输入文件格式的输出文件”。

I need to know how to print all the info in the main to an output file with the same format as the input file and I use here ArrayList.我需要知道如何将 main 中的所有信息打印到与输入文件格式相同的输出文件中,我在这里使用 ArrayList。 it's working fine when I print the name and the height but when I want to print season or score, an exception appears.当我打印名称和高度时它工作正常,但是当我想打印季节或得分时,会出现异常。

pw.write(t1.getName() + "; " + t1.getCity() + "\n");
for (int m = 0; m < p2.size(); m++) {
    pw.print(t1.getPlayerList().get(m).getName() + "; " + t1.getPlayerList().get(m).getHeight() + "; ");
    pw.println(t1.getPlayerList().get(m).getSeasonalRecords().get(m).getScores());
} 

it works well, but when I write它运作良好,但当我写

pw.println(t1.getPlayerList().get(m).getSeasonalRecords().get(m).getScores());

appear something is wrong that the exceptions that I got出现一些错误,我得到的例外

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2 at java.util.ArrayList.rangeCheck(ArrayList.java:657) at java.util.ArrayList.get(ArrayList.java:433)线程“main”中的异常 java.lang.IndexOutOfBoundsException: Index: 2, Size: 2 at java.util.ArrayList.rangeCheck(ArrayList.java:657) at java.util.ArrayList.get(ArrayList.java:433)

The root cause of the issue is described in the comments: index m exceeds the number of seasonal records and definitely it may take another nested loop to print the seasonal records.问题的根本原因在评论中描述:索引m超过了季节性记录的数量,并且肯定可能需要另一个嵌套循环来打印季节性记录。

It may be better to replace for loops with indexes with for-each to make the code shorter, more readable and less prone to the mentioned errors:for-each索引替换for循环可能会更好,以使代码更短、更易读且不易出现上述错误:

for (var player : t1.getPlayerList()) {
    pw.println(player.getName() + "; " + player.getHeight() + "; ");

    for (var seasonRecord : player.getSeasonalRecords()) {
        pw.println(seasonalRecord.getScores());
    }
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM