虽然循环不检查两个条件?

时间:2018-09-30 00:41:29

标签: java error-handling

我对编程还很陌生,因此决定承担一个在控制台中创建游戏的项目。用户可以选择从3x3网格区域的中心向上,向下,向左或向右移动。 x,y位置之一标记为“坏”正方形,并且当用户的x和y等于坏正方形的x和y时,游戏结束。正方形的错误位置是x = 1y = 3

我遇到的问题是,当用户输入向上或向左(因此用户y变为3或用户x变为1)并且游戏结束时,即使其他轴值之一与该错误平方都不匹配。

这是我的代码:

public static void main (String[]args){
    //scanner
    Scanner userIn = new Scanner(System.in);

    //string that will get users value
    String movement;

    //strings that are compared to users to determine direction
    String up = "Up";
    String down = "Down";
    String left = "Left";
    String right = "Right";

    //starting coordinates of user
    int x = 2;
    int y = 2;

    //coordinates of bad square
    int badx = 1;
    int bady = 3;

    //message telling user options to move (not very specific yet)
    System.out.println("Up, Down, Left, Right");

    //do while loop that continues until 
    do {
        movement = userIn.nextLine();

        //checking user input and moving them accordingly
        if (movement.equals(up)) {
            y++;
        } else if (movement.equals(down)) {
            y--;
        } else if (movement.equals(left)) {
            x--;
        } else if (movement.equals(right)) {
            x++;
        } else {
            System.out.println("Unacceptable value");
        }

        //checking if user is out of bounds, if user tries to leave area, x or y is increased or decreased accordingly
        if (x < 0 || y < 0 || x > 3 || y > 3) {
            System.out.println("Out of bounds");
            if (x < 0) {
                x++;
            } else if (y < 0) {
                y++;
            } else if (x > 3) {
                x--;
            } else if (y > 3) {
                y--;
            }
        }
        //message showing user x and y coordinates
        System.out.println("x =" + x + " y =" + y);
    } while (y != bady && x != badx); //what checks to see if user has come across the bad square

    //ending message (game ends)
    System.out.println("Bad Square. Game over.");
}

3 个答案:

答案 0 :(得分:2)

您的while(y != bady && x != badx)测试y不错,并且x不错,因此只需要其中之一成为false就可以停止循环。

一个简单的解决方法可能是交换一些逻辑。

while(!(y == bady && x == badx))

答案 1 :(得分:1)

如果考虑条件语句如何用while(y != bady && x != badx)表示,您将看到,当x = 1y = 3时,AND语句中的任一边都为假,并导致整个条件为假。您可以通过编写以下内容来处理它:

while(y != bady || x != badx)

答案 2 :(得分:0)

只需在条件下设置逻辑或 while(y!= bady || x!= badx);

&&认为两个条件都应为真