我一直坚持用Java来解决餐饮哲学家的问题。
我得到的错误是
"线程中的异常" main" java.lang.ArrayIndexOutOfBoundsException:2 在Main.main(Main.java:43)"
第43行是:
rFork = forks[forI + 1];
并且位于
下面的for循环中
for (int i = 0; i < phiNum; i++)
{
list[i] = new Philosopher(forks[i], forks[(i + 1) % phiNum],
i, in.nextFloat());
for (int forI = 0; forI < (phiNum); forI++)
{
lFork = forks[forI];
rFork = forks[forI + 1];
}
}
以下是Main.java类的其余代码:
import java.util.*;
public class Main
{
static Scanner in = new Scanner(System.in);
public static void main(String[] args)
{
int phiNum = 0, maxForks = 2;
float time = 0;
System.out.print("Enter the number of Philosophers: ");
phiNum = in.nextInt();
//float timeSpentThinking = in.nextFloat();
Philosopher[] list = new Philosopher[phiNum];
Fork[] forks = new Fork [phiNum];
Fork lFork = new Fork();
Fork rFork = new Fork();
if (phiNum == 0)
System.out.println("There are no philosophers eating or
thinking.");
else if (phiNum == 1)
System.out.println("There are not enough forks for the
philosopher" + " to eat.");
else
{
for (int index = 0; index < (phiNum); index++)
forks[index] = new Fork();
for (int i = 0; i < phiNum; i++)
{
list[i] = new Philosopher(forks[i], forks[(i + 1) % phiNum],
i, in.nextFloat());
for (int forI = 0; forI < (phiNum); forI++)
{
lFork = forks[forI];
rFork = forks[forI + 1];
}
}
}
for (int i = 1; i < list.length; i++)
list[i].run();
}
}
答案 0 :(得分:0)
您声明此变量:
forNum = 0;
并使用它来声明数组:
Fork[] forks = new Fork [forNum];
所以数组是空的,所以试图访问它会给你带来错误。您必须为变量forNum
提供非零值,或者要求用户输入分叉数:
System.out.print("Enter the number of forks: ");
forNum = in.nextInt();
学习使用调试器可以帮助您看到数组的大小为零。