我班级出现意外错误

时间:2017-11-05 22:37:53

标签: java

在编写课程时,它会给我一个预期的令牌错误,我无法弄清楚如何解决它或为什么它会给我。

以下是代码:

public class SetUpDoors {

private int DoorAmount;
private int WinningDoorAmount; 
private int[] DoorArray= new int[DoorAmount];
private int winnerSelect = 0;

for (int i = 0; i < DoorAmount; i++) {
    if (WinningDoorAmount > 0) {
        winnerSelect = (int) Math.round( Math.random());
        DoorArray[i] = winnerSelect;
        if(winnerSelect == 1) {
            WinningDoorAmount--;
        }
    }
    else {
        DoorArray[i] = 0;
    }
    DoorAmount--;
}

void setDoorAmount(int userDoors){
    DoorAmount = userDoors;
}
void setWinningDoorAmount(int userWinningDoors) {
    WinningDoorAmount = userWinningDoors;
}

}

它给出了错误;在private int winnerSelect = 0;的末尾 以及DoorAmount--;下面的}的错误 第一个是预期的标记“{”,第二个是添加“}”来完成阻止。

2 个答案:

答案 0 :(得分:2)

您必须在方法中声明以下代码。

例如:

public void newMethod(){
 for (int i = 0; i < DoorAmount; i++) {
 if (WinningDoorAmount > 0) {
    winnerSelect = (int) Math.round( Math.random());
    DoorArray[i] = winnerSelect;
    if(winnerSelect == 1) {
        WinningDoorAmount--;
    }
  }
 }
 else {
    DoorArray[i] = 0;
 }
  DoorAmount--;
}

答案 1 :(得分:1)

试试这个

public class SetUpDoors {

    private int DoorAmount;
    private int WinningDoorAmount; 
    private int[] DoorArray= new int[DoorAmount];
    private int winnerSelect = 0;

    {
        for (int i = 0; i < DoorAmount; i++) {
        if (WinningDoorAmount > 0) {
            winnerSelect = (int) Math.round( Math.random());
            DoorArray[i] = winnerSelect;
            if(winnerSelect == 1) {
                WinningDoorAmount--;
            }
        }
        else {
            DoorArray[i] = 0;
        }
        DoorAmount--;
        }
    }

    void setDoorAmount(int userDoors){
        DoorAmount = userDoors;
    }
    void setWinningDoorAmount(int userWinningDoors) {
        WinningDoorAmount = userWinningDoors;
    }
}