arrays - Need help fixing java.lang.ArrayIndexOutOfBoundsException -
i'm trying implement this word wrap algorithm in java. program takes in number of paragraphs wrap, maximum line length, , input text. example:
1 5 test.
however, after takes in input text , runs algorithm, following runtime error:
exception in thread "main" java.lang.arrayindexoutofboundsexception: 1 @ dynamicprogramming.main(dynamicprogramming.java:74) @ sun.reflect.nativemethodaccessorimpl.invoke0(native method) @ sun.reflect.nativemethodaccessorimpl.invoke(nativemethodaccessorimpl.java:57) @ sun.reflect.delegatingmethodaccessorimpl.invoke(delegatingmethodaccessorimpl.java:43) @ java.lang.reflect.method.invoke(method.java:601) @ com.intellij.rt.execution.application.appmain.main(appmain.java:120)
could possible have typo translating above code c++ java, or there kind of error in logic causing exception? thanks.
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]; (int i=1; <= n; i++) { extraspaces[i][i] = m - inputlinelengths[i-1]; (int j=i+1; j <= n; j++) { extraspaces[i][j] = extraspaces[i][j-1] - inputlinelengths[j-1] -1; } } (int i=1; i<= n; i++) { (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; (int j=1; j <= n; j++) { optimaltotalcost[j] = double.positive_infinity; (int i=0; <= 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[]{}; (int i=1; <= p; i++) { m = integer.parseint(scanner.nextline()); inputline = scanner.nextline().split("[ ]+"); inputlinelengths[i] = inputline.length; printneatly(m, inputlinelengths); } } }
just looking @ printneatly
method:
you length of array this:
int n = inputlinelengths.length;
but in loops, go , including n
:
for (int i=1; <= n; i++) {
you need stop before, because arrays (in java) indexed 0
n-1
(so it's mean start arrays 0
, , not 1
)
for (int i=1; < n; i++) {
Comments
Post a Comment