我正在尝试在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);
}
}
}
答案 0 :(得分:1)
只需查看printNeatly
方法:
你得到这样的数组的长度:
int n = inputLineLengths.length;
但是在你的循环中,你可以选择n
:
for (int i=1; i <= n; i++) {
你需要在之前停止,因为数组(在Java中)从0
索引到n-1
(因此你很可能意味着从{{{{{{{{ 1}},而不是0
)
1
答案 1 :(得分:0)
首先,您的inputLineLengths
数组初始化为0
长度,因此您无法将任何内容放入数组中。
首先将其初始化为P
长度。
int[] inputLineLengths = new int[P];
其次,您的for
循环需要覆盖有效索引值,范围从0
到array's length - 1
。将您的for
循环更改为:
for (int i = 0; i < P; i++) {
for
之外的其他main
循环需要进行类似的更改。