我正在尝试用Java实现Banker算法,但在加载数组时遇到了问题。这是我正在使用的代码
public static void main(String[] args) throws FileNotFoundException {
String filename = null;
int need[][];
int allocate[][];
int max[][];
int available[][];
int n = 0;
int m = 0;
int lineCount = 0;
Scanner in = new Scanner(System.in);
System.out.println("Enter the file name.");
filename = in.nextLine();
File textFile = new File(filename);
Scanner input = new Scanner(textFile);
max = new int[n][m];
allocate = new int[n][m];
need = new int[n][m];
available = new int[1][m];
n = input.nextInt();
m = input.nextInt();
System.out.print("Number of Processes: " + n);
System.out.print("nNumber of Processes: " + m);
max = new int[n][m];
allocate = new int[n][m];
need = new int[n][m];
available = new int[1][m];
String line = input.nextLine();
while (line != null && lineCount < n) {
String[] temp = line.split(" ");
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
allocate[i][j] = Integer.parseInt(line);
System.out.println("here");
}
line = input.nextLine();
lineCount++;
}
}
}
我的示例文件包含这些数据。
5
4
0 0 1 21 0 0 01 3 5 40 6 3 20 0 1 4
0 0 1 21 7 5 02 3 5 60 6 5 20 6 5 6
1 5 2 0
凌晨1:00 4 2 0
所以,在尝试这样做的时候,我遇到了很多不同的错误。现在我得到一个NumberFormatException:For输入字符串"错误。非常感谢您的帮助。
你有一堆非常小的数组,而且你永远不会增加它们的大小:
int n = 0;
int m = 0;
...
max = new int[n][m]; // 0x0 array, unused
allocate = new int[n][m]; // 0x0 array, likely the culprit
need = new int[n][m]; // 0x0 array, unused
available = new int[1][m]; // 1x0 array, unused
在这些数组中,只使用allocate
,稍后将在for循环中使用它:
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
// OutOfBounds is probably here:
allocate[i][j] = Integer.parseInt(line);
System.out.println("here");
}
line = input.nextLine();
lineCount++;
}
此外,您正在运行Integer.parseInt(line)
,它正试图解析整行内容。您应该一次只解析一个令牌,它将是Integer.parseInt(temp[someindex])
。