【发布时间】:2014-07-19 15:51:41
【问题描述】:
我正在尝试在 Java 中实现 this word wrap algorithm。我的程序包含要换行的段落数、最大行长和输入文本。例如:
1
5
This is a test.
但是,在它接受输入文本并运行算法后,我收到以下运行时错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at DynamicProgramming.main(DynamicProgramming.java:74)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
在将上述代码从 C++ 转换为 Java 时,是否有可能出现拼写错误,或者此逻辑中是否存在某种错误会导致此异常?谢谢。
import java.util.Scanner;
public class DynamicProgramming {
static int P;
static int M;
static String[] inputLine;
public static void printNeatly(int M, int[] inputLineLengths) {
int n = inputLineLengths.length;
double[][] extraSpaces = new double[n][n];
double[][] lineCost = new double[n][n];
double[] optimalTotalCost = new double[n];
int[] optimizedLengths = new int[n];
for (int i=1; i <= n; i++) {
extraSpaces[i][i] = M - inputLineLengths[i-1];
for (int j=i+1; j <= n; j++) {
extraSpaces[i][j] = extraSpaces[i][j-1] - inputLineLengths[j-1] -1;
}
}
for (int i=1; i<= n; i++) {
for (int j=i; j <=n; j++) {
if (extraSpaces[i][j] < 0) {
lineCost[i][j] = Double.POSITIVE_INFINITY;
}
else if (j == n && extraSpaces[i][j] >= 0) {
lineCost[i][j] = 0;
}
else {
lineCost[i][j] = extraSpaces[i][j]*extraSpaces[i][j];
}
}
}
optimalTotalCost[0] = 0;
for (int j=1; j <= n; j++) {
optimalTotalCost[j] = Double.POSITIVE_INFINITY;
for (int i=0; i <= j; i++) {
if (optimalTotalCost[i-1] != Double.POSITIVE_INFINITY && lineCost[i][j] != Double.POSITIVE_INFINITY &&
(optimalTotalCost[i-1] + lineCost[i][j] < optimalTotalCost[j])) {
optimalTotalCost[j] = optimalTotalCost[i-1] + lineCost[i][j];
optimizedLengths[j] = i;
}
}
}
}
public int printOutput(int[] optimizedLengths, int n) {
int k;
if (optimizedLengths[n] == 1) {
k = 1;
}
else {
k = printOutput(optimizedLengths, optimizedLengths[n]-1);
}
System.out.println(optimizedLengths[n]);
return k;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
P = Integer.parseInt(scanner.nextLine());
int[] inputLineLengths = new int[]{};
for (int i=1; i <= P; i++) {
M = Integer.parseInt(scanner.nextLine());
inputLine = scanner.nextLine().split("[ ]+");
inputLineLengths[i] = inputLine.length;
printNeatly(M, inputLineLengths);
}
}
}
【问题讨论】:
-
你试过使用调试器吗?
-
实际上,我以前从未使用过 Java 调试器。 jdb 可以吗?
-
您的 IDE 应该带有一个不错的 GUI 调试器。对于这样的代码,还可以考虑编写单元测试。它们可以极大地帮助查找错误。
-
我实际上并不熟悉命令行调试器。我一直用 Eclipse 的……抱歉,我帮不上忙
-
谢谢。我使用 IntelliJ IDEA,所以我会研究一下。
标签: java arrays indexoutofboundsexception