我一直收到这个错误:
线程中的异常" main"显示java.lang.NullPointerException
at ButtonsLab.pvc1(ButtonsLab.java:110)
at ButtonsLab.main(ButtonsLab.java:155)
有些人问过这个问题,但我似乎无法找到解决这个问题的人。我知道它与pvc1()方法中的数组有关。
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Random;
class ButtonsLab
{
ArrayList<Integer> buttons;
ButtonsLab(){
buttons = new ArrayList<Integer>();
}
public void fillMyArray(){
for(int i = 0; i < 5; i++){
buttons.add(i + 1);
}
}
public static int pvp(int buttonNum){
Scanner in = new Scanner(System.in);
int player1 = 0;
int player2 = 0;
int x = 0; //determines who wins
while (buttonNum > 1){
while (player1 < 1 || player1 > 3){
System.out.println("Player 1: How many buttons do you take?(1-3)");
player1 = in.nextInt();
}
buttonNum -= player1;
if(buttonNum != 1){
System.out.println("There are " + buttonNum + " Buttons on the board.");
}
else{
System.out.println("... There is 1 Button on the board.");
}
if(buttonNum == 1){
x = 1;
}
else{
while (player2 < 1 || player2 > 3){
System.out.println("Player 2: How many buttons do you take?(1-3)");
player2 = in.nextInt();
}
}
buttonNum -= player2;
if(buttonNum != 1){
System.out.println("There are " + buttonNum + " Buttons on the board.");
}
else if(x !=1){
System.out.println("... There is 1 Button on the board.");
}
player1 = 0;
player2 = 0;
}
if(x == 1){
while (player2 < 1 || player2 > 3){
System.out.println("Player 2: How many buttons do you take?(1-3)");
player2 = in.nextInt();
}
System.out.println("Player 2, you lose.");
}
else{
while (player1 < 1 || player1 > 3){
System.out.println("Player 1: How many buttons do you take?(1-3)");
player2 = in.nextInt();
}
System.out.println("Player 1, you lose.");
}
return x;
}
public static int pvc1(int buttonNum){
Scanner in = new Scanner(System.in);
int player1 = 0;
int x = 0; //determines who wins
ButtonsLab [] aiChoice;
aiChoice = new ButtonsLab[buttonNum];
for(int i = 0; i < aiChoice.length; i++){
aiChoice[i].fillMyArray();
}
while (buttonNum > 1){
while (player1 < 1 || player1 > 3){
System.out.println("Player 1: How many buttons do you take?(1-3)");
player1 = in.nextInt();
}
buttonNum -= player1;
int rnd = new Random().nextInt(aiChoice.length);
System.out.println("AI selects " + rnd);
player1 = 0;
}
return x;
}
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
int buttonNum = 0;
int gameOpt = 0;
while (buttonNum < 10 || buttonNum > 100){
System.out.println("How many buttons are on the board initially?(10-100)");
buttonNum = in.nextInt();
}
System.out.println("Options: Play against a friend (1) Play against easy computer (2) Play against hard computer (3)");
gameOpt = in.nextInt();
switch(gameOpt){
case 1:
pvp(buttonNum);
break;
case 2:
pvc1(buttonNum);
break;
}
}
}
答案 0 :(得分:0)
完成此操作后
aiChoice = new ButtonsLab[buttonNum];
数组中充满了&#39; nulls&#39;。你需要这样做(对于数组中的每个位置)
aiChoice[i] = new ButtonsLab();
之前你可以这样做:
aiChoice[i].fillMyArray();