而Loop状态未被检查

时间:2015-08-02 08:25:53

标签: java eclipse

 import java.util.Scanner;

public class CollatzSequence {
static int pileA = 3;
static int pileB = 3;
static int pileC = 3;

static String choice = "";
static int turn = 1;
static int remove = 0;

public static void main(String[] args) {
    int newA = 3;
    int newB = 3;
    int newC = 3;
    Scanner scan = new Scanner(System.in);
    System.out.println("Player 1: ");
    String p1 = scan.next();
    System.out.println("Player 2: ");
    String p2 = scan.next();

    while (newA != 0 || newB != 0 || newC != 0) {

        if (turn == 1) {
            System.out.println("PileA: " + newA + "PileB: " + newB + "PileC:     " + newC);

            System.out.println("Choose pile " + p1);
            choice = scan.next();
            if (choice.equals("A")) {
                System.out.println("Remove how much?");
                remove = scan.nextInt();
                newA = pileA - remove;
                pileA = newA;
                turn = 2;
            }

            if (choice.equals("B")) {
                System.out.println("Remove how much?");
                remove = scan.nextInt();
                newB = pileB - remove;
                pileB = newB;
                turn=2;
            }
            if (choice.equals("C")) {
                System.out.println("Remove how much?");
                remove = scan.nextInt();
                newC = pileC - remove;
                pileC = newC;
                turn = 2;
            }

        }
        if (turn == 2) {
            System.out.println("PileA: " + newA + "PileB: " + newB + "PileC: " + newC);
            System.out.println("Choose pile " + p2);
            choice = scan.next();
            if (choice.equals("A")) {
                System.out.println("Remove how much?");
                remove = scan.nextInt();
                newA = pileA - remove;
                pileA = newA;
                turn = 1;
            }

            if (choice.equals("B")) {
                System.out.println("Remove how much?");
                remove = scan.nextInt();
                newB = pileB - remove;
                pileB = newB;
                turn = 1;
            }
            if (choice.equals("C")) {
                System.out.println("Remove how much?");
                remove = scan.nextInt();
                newC = pileC - remove;
                pileC = newC;
                turn = 1;
            }

        }

    }


}
}

这应该模拟一个基本的nim游戏。玩家不断从堆栈中移除,直到没有剩下。问题是循环没有终止。虽然我无法确定它,但我认为它在我的可见性修饰符中/ if语句从turn = 1到turn = 2来回传递。

1 个答案:

答案 0 :(得分:0)

我会用:

if(turn == 1){
    ...
}
else{       //for turn ==2
    ...
}

因为问题出现在情况中,当第一个玩家移动后所有桩都是空的(并且你仍然要求玩家2移动,无论他选择什么(!= 0)移动后都会有一堆不相等为0,所以while中的语句将返回true)。

另一种方法while (newA >= 0 || newB >= 0 || newC >= 0)但是那时仍然可能有一个不必要的动作(对于玩家2)。

如果我错过了什么,请告诉我,但这应该有用。