This is my code and when I run my program with this "java code1 3 < test.txt
"
the test txt file contain 3 x 3 numbers grid.
(47 49 14
73 4 30
2 69 71)
and supposed to output 191
instead it gives me this error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
at code1.main(code1.java:37)
the purpose of this java program is to reads as a command-line argument a number n, this number is the number of columns and rows mentioned above. -It then reads from standard input n * n integers, each integer being between zero (0) and one hundred (100), and then writes to standard out a single integer representing the maximum possible profit
============
//args[0]=n
//args[1]=grid.txt(should be present in same directory as of your code)
import java.util.*;
import java.io.*;
import java.lang.*;
public class code1{
static int findMaxPath(int grid[][], int n) {
int result = -1;
// loop to find maximum if grid has n=1
for (int i = 0; i < n; i++) {
result = Math.max(result, grid[0][i]);
}
for (int i = 1; i < n; i++) {
result = -1;
for (int j = 0; j < n; j++) {
if (j > 0 && j < n - 1) // when he can come from both left-up or right-up part
{
grid[i][j] += Math.max(grid[i - 1][j - 1], grid[i - 1][j + 1]);
} else if (j > 0) // when he can come from right-up part
{
grid[i][j] += grid[i - 1][j - 1];
} else if (j < n - 1) // when he can come from left-up part
{
grid[i][j] += grid[i - 1][j + 1];
}
result = Math.max(grid[i][j], result);
}
}
return result;
}
public static void main(String args[]) throws IOException {
int n = Integer.parseInt(args[0]);
File file = new File(args[1]);
BufferedReader br = new BufferedReader(new FileReader(file));
int grid[][] = new int[n][n];
String line;
int i = 0;
while ((line = br.readLine()) != null) {
String arr[] = line.split(" ");
for (int j = 0; j < n; j++) {
grid[i][j] = Integer.parseInt(arr[j]);
}
i++;
}
System.out.println(findMaxPath(grid, n));
}
}