【问题标题】:Java java.lang.ArrayIndexOutOfBoundsException: 3 error messageJava java.lang.ArrayIndexOutOfBoundsException: 3 错误消息
【发布时间】:2015-08-29 05:15:14
【问题描述】:

所以我的代码在测试showSortedRows() 方法时除外。它向我展示了我想要的输出,但同时给了我这个错误消息。我真的不知道为什么,请帮助我!

错误消息:线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 3
在 Driver0.showSortedRows(Driver0.java:90)
在 Driver0.choice(Driver0.java:35) 在 Driver0.main(Driver0.java:21)

import java.io.*;
import java.util.*;
public class Driver0
{
   public static int [][] array;
   public static int dimension1, dimension2;
   public static void main(String[] args)
   {
      Scanner input = new Scanner(System.in);
      System.out.println("Welcome to Project 0.");
      System.out.println("What is the name of the data file? ");
      System.out.print("> ");
      String file = input.nextLine();
      readFile(file);
      String nextCommand = "";
      while (!(nextCommand.equals("quit"))) 
      {
         System.out.println("\nNext command");
         System.out.print("> ");
         nextCommand = input.nextLine();
         choice (nextCommand);
      }

   }

   public static void choice(String command) 
   {
      switch (command) 
      {
         case "help": System.out.println("show array\nwhich rows sorted\nwhich cols sorted"+
                                     "increase row i by n\nincrease col j by n\nquit\n");
                  break;
     case "show array": showArray();
                        break;
     case "which rows sorted": showSortedRows();
                               break;
     /*case "which cols sorted": showSortedCols();
     case "increase row i by n": increaseRow();
     case "increase col j by n": increaseCol();*/

      }
   }


    public static void readFile(String file)
    {
       try
       {
            Scanner sc = new Scanner(new File(file));
            dimension1 = sc.nextInt();
            dimension2 = sc.nextInt();
            array = new int[dimension1][dimension2];
            while (sc.hasNext()) 
            {
                for (int row = 0; row < dimension1; row++)
                {
                for (int column = 0; column < dimension2; column++) 
                {
                     array[row][column] = sc.nextInt();
                }
             }

            }
             sc.close();
          }

         catch(Exception e)
         {
             System.out.println("Error: file not found or insufficient       requirements.");
          }
          }
         public static void showArray() 
         {
              for (int rows = 0; rows < dimension1; rows++) 
              {
                    for (int col = 0; col < dimension2; col++) 
                    {
                         System.out.printf("%2d ", array[rows][col]);
                    }
                    System.out.println();
                 }
              }

             public static void showSortedRows()
             {
                  for (int rw = 0; rw < dimension1; rw++)
                  {
                      for (int cl = 0; cl < dimension2; cl++)
                      {
                         if (array[rw][cl] <= array[rw][cl+1])
                         System.out.printf("%2d,", rw);
                         rw++;
                      }
                      System.out.println();
                    }     

                 }

              }

【问题讨论】:

  • 你知道如何阅读异常堆栈跟踪和调试你的代码吗?

标签: java exception compiler-errors syntax-error


【解决方案1】:

您的循环一直运行到cl &lt; dimension2,所以array[rw][cl+1] 将导致错误。

您必须将循环更改为for (int cl = 0; cl &lt; dimension2-1; cl++)

【讨论】:

  • 我像你说的那样修复了它,但它仍然给了我同样的错误,所以我不知道发生了什么
  • @SylviaWang 你确定你已经清理并重建了你的项目吗?
  • @Jens 如果维度 2 > 维度 1,rw++ 也会导致 ArrayIndexOutOfBoundsException。
  • @Gosu Oh 已经监督过了。
  • @SylviaWang 不要改变它里面的 Loop 的变量。这是非常糟糕的做法。
【解决方案2】:

就是这一行:

if (array[rw][cl] <= array[rw][cl+1])

当 cl 为 dimension2-1 时,cl + 1 会导致 ArrayIndexOutOfBoundsException

顺便问一下,你确定双 for 循环中的 rw++ 是正确的吗?
它应该是if 条件的一部分吗?
当dimensions2>dimensions1时,也会导致ArrayIndexOutOfBoundsException


showSortedRows() 应该是:

public static void showSortedRows() {
    for (int rw = 0; rw < dimension1; rw++) {
        boolean sortedRow = true;
        StringBuilder sb = new StringBuilder();
        for (int cl = 0; cl < (dimension2 - 1); cl++) {
            sb.append(array[rw][cl]).append(" ");
            if (array[rw][cl] > array[rw][cl + 1]) {
                sortedRow = false;
            }
            if((cl + 1) == (dimension2 - 1)) {
                sb.append(array[rw][cl + 1]).append(" ");
            }
        }
        if(sortedRow) {
            System.out.println("Row " + (rw + 1) + " is sorted!");
            System.out.println("Row contents: " + sb.toString());
        }
    }
}

输出:

Row 1 is sorted!
Row contents: 2 3 4 5 10 
Row 3 is sorted!
Row contents: -3 -1 0 1 5 

【讨论】:

  • 我修复了它,就像你发布的一样,但它仍然给了我同样的错误
  • @SylviaWang 那么你需要告诉我们错误是什么?在您的问题中包含输入文件的内容。
  • 我用过 rw++;是因为我想打印出所有排序的行号,所以我认为这是正确的,但我不确定它是否应该在 if 中。
  • 输入文件的内容是这样的:3 5 2 3 4 5 10 4 5 2 3 7 -3 -1 0 1 5
  • @SylviaWang 删除rw++ 看看效果如何?这没有意义。
【解决方案3】:

因为这条线而发生:

 if (array[rw][cl] <= array[rw][cl+1])  

发生的情况是,当您的变量 cl 在内部循环的最后一次迭代中变为等于 dimension2 - 1 时,它会检查 [cl][dimension2]th 索引。数组中不存在哪个。您的数组的大小为[row][dimension2],这意味着它的计数从0row - 1 用于行和0dimension2 - 1 用于列。它仍然试图访问dimension2th 索引。因此它会给你ArrayIndexOutOfBoundsException

解决方案:

你的循环必须是:

for(int cl = 0; cl < dimension2 - 1; cl ++)  

希望这会有所帮助:)

【讨论】:

  • 我试着像你说的那样改变它,但我得到的错误信息和上面的完全一样,没有任何改变,所以很奇怪。
  • 嘿,因为你试图在循环体中增加rw。您确定要在内循环中的 if 语句后面加上 rw++ 吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-29
  • 2019-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多