【问题标题】:how to avoid index out of bound exception when displaying the whole data显示整个数据时如何避免索引越界异常
【发布时间】:2021-05-14 00:43:34
【问题描述】:
//test class

public class Test {
public static ArrayList<sports> listofsports;
    public static ArrayList<group> listofGroups;
    private static Object IOException;

我在 listofGroups 数组列表中添加了 10 个组 和 3 个运动到 listofsports 数组列表

//显示全部数据

public  static void displaywholedata() {
 
    int i;

    for (i = 0; i < listofGroups.size(); i++) {
        for (int j = 0; j < listofsports.size(); j++) {

            System.out.println(listofsports.get(i).getSportsplayed() + " " + listofsports.get(i).getListofgroups().get(j).getThenamegroup() + " ");
        } 

    } 


displaywholedata(); }

给我的错误

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
    at java.util.ArrayList.rangeCheck(ArrayList.java:659)
    at java.util.ArrayList.get(ArrayList.java:435)
    at Test.displaywholedata(Test.java:52)
    at Test.main(Test.java:139)
Command execution failed.

谁能帮我检测一下我的代码哪里出了问题

【问题讨论】:

  • 你怎么知道listofGroupslistofsports 大小相同?你检查ilistofGroups,然后用它来索引listofsports。 - 实际上,第二个想法看起来你有 ij 颠倒了:-)
  • 请提供运动和团体的定义
  • 你的Test 类甚至可能没有这个listofsports.get(i).getListofgroups().get(j) 结构。
  • getlistofgroups 是体育课组列表的getter

标签: java oop exception


【解决方案1】:
for (i = 0; i < listofGroups.size(); i++) {
    for (int j = 0; j < listofsports.size(); j++) {
        System.out.println(listofsports.get(i).getSportsplayed() + " " + listofsports.get(i).getListofgroups().get(j).getThenamegroup() + " ");
    }

i 是 0 到 listofGroups.size() 但随后您使用 i 访问 listofsports

j 是 0 到 listofsports.size() 但是你使用 j 访问 listOfGroups

你已经交换了 i 和 j。要么交换 println 中的所有 is 和 js,要么交换 for 循环中的 is 和 js。惯例规定 for 循环是正确的,因此请更改 println。

【讨论】:

  • 我尝试换入 println 但错误仍然存​​在
  • 那么您需要将 ypur println 拆分为 3 行,以查看哪个 get() 失败 - 您是否更改了所有 3 行?
猜你喜欢
  • 2012-01-31
  • 2013-10-05
  • 2015-01-31
  • 1970-01-01
  • 2019-06-09
  • 1970-01-01
  • 2012-06-19
  • 2018-11-19
  • 2013-03-30
相关资源
最近更新 更多