我幾乎是一個編程noob,但我已經研究過所有的地方,找不到答案。即時通訊使用Eclipse和每一次我運行我的程序時,它說:ArrayIndexOutOfBoundsException當循環
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at computer.guess(game1player2.java:24)
at game1player2.main(game1player2.java:39)
這裏是我的代碼:
import java.util.Scanner;
class computer{
int g = 0;
int[] compguess = new int[g];
void guess(){
int rand;
while(0 < 1){
int i;
rand = (int) Math.ceil(Math.random()*10);
for (i = 1; i < compguess.length; i++){
if(rand == compguess[i]){
break;
}
}
if(i > compguess.length){
g++;
rand = compguess[g];
System.out.println(compguess[compguess.length]);
}
}
}
}
public class game1player2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
computer computer1 = new computer();
for(int a = 0; a < 2; a++){
computer1.guess();
for(int n = 0; n <= computer1.compguess.length; n++)
System.out.println(computer1.compguess[n]);
}
{
input.close();
}
}
}
我現在真的很迷茫,我試圖讓計算機生成一個隨機數1 10,但是如果它已經在數組中生成另一個。
'n <= computer1.compguess.length'應改爲'<'。 '<='表示你正在做0-> n,這實際上是n + 1次迭代。例如0,1,2,3,4是一個5項數組,但實際上你迭代了0,1,2,3,4,5,最後嘗試訪問數組末尾的1個元素。 –
爲什麼'while(true)'而不是'while(0 <1)'? –