【发布时间】: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