gpt4 book ai didi

java - Java java.lang.ArrayIndexOutOfBoundsException : 3 error message

转载 作者:行者123 更新时间:2023-12-02 10:43:00 25 4
gpt4 key购买 nike

因此,除了测试showSortedRows()方法时,我的代码均有效。它显示了我想要的输出,但同时给了我此错误消息。我真的不知道为什么,请帮助我!

Error message: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at Driver0.showSortedRows(Driver0.java:90)
at Driver0.choice(Driver0.java:35) at 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();
}

}

}

最佳答案

您的循环一直运行到cl < dimension2为止,因此array[rw][cl+1]将导致错误。

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

关于java - Java java.lang.ArrayIndexOutOfBoundsException : 3 error message,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30815864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com