简体   繁体   中英

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."

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. 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)

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.

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 (var player : t1.getPlayerList()) {
    pw.println(player.getName() + "; " + player.getHeight() + "; ");

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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