虽然循环在Java中意外地表现

时间:2014-05-15 17:30:29

标签: java loops while-loop finch

我试图让我的循环一遍又一遍,直到用户键入“退出”然后它将退出。

基本上我试图让我的Finch机器人根据它的位置改变鼻子的颜色,但我很困惑如何让它在允许用户定位之后再次定位它以便鼻子颜色可以多次改变颜色。首次运行时,Finch将执行代码,但之后立即退出。

这是我的代码:

public class finch {

public static final int INCREASE = 20;
public static final int SEC = 1000;
public static final int MAXSPEED = 255;
public static final int HALFSEC = 500;

public static Finch myFinch;
public static void main(String[] args) {
    myFinch = new Finch();

    Menu();

}

public static void Menu() {

    Scanner console = new Scanner(System.in);

    System.out.println("Enter your choice:" + "");

    int input;
    int input1;

    boolean flag=true;
    while(flag){

        System.out.println("1.\t" + "Rolling" + "Finch");
        System.out.println("2.\t" + "Obedient" + "Finch");
        System.out.println("3.\t" + "Exit");
        System.out.println();
        System.out.println("Enter your choice:");
        System.out.println();


        input = console.nextInt();
        flag=false;
        if (input == 1) {
            //input = DarkFinch;
            System.out.println("Position the Finch \"down\" or \"up\" to change nose color");
            rolling(myFinch);
        } else if (input == 2) {
            // input = ChasetheFinch;
            //  System.out.println("Chase The Finch");
        } else if (input == 3) {
            //    input = Exit;
            System.out.println("Goodbye");
        } else {
            //    System.out.println("Try again");

            flag=true;
            /*  return Menu(); */
        }
    }
}

public static boolean rolling(Finch myFinch) {//This method will change the Finches nose color depending on the Finches position.
    //"up" = place the finch upright standing on its tail



    for (int i = 1; i <= 20; i++) {


        while (myFinch.isBeakDown() || myFinch.isBeakUp()) {
            if (myFinch.isBeakDown()) {
                myFinch.setLED(0,0,255,3000);
            } else if (myFinch.isBeakUp()) {
                myFinch.setLED(255,0,0,3000);
            } else {
                myFinch.setLED(0,0,0,5000);
            }
        }

    }
    return true;
}

}

1 个答案:

答案 0 :(得分:1)

在输入值的条件之前,不要设置flag = false。在if(input == 3)case

中将其设置为false