在选择正确答案之前,我如何继续使用此代码?

时间:2013-12-13 21:42:09

标签: java cmd

我希望这段代码能够继续,直到输入一个可接受的答案(即1,2,3,4),但我不知道怎么做。谢谢。此外,如果有任何其他方式可以简化这也将有所帮助。

import java.util.Scanner;
public class NewMain {
    public static void main(String[] args) {
        String input;
        Scanner keyboard =  new Scanner(System.in);

        System.out.println("Your choice\n[1]Up \n[2]Down \n[3]Left \n[4]Right");
        input = keyboard.nextLine();

        if(input.equals("1")) {
            System.out.println("You are going up!!!");
        }
        else {
            if(input.equals("2")){
                System.out.println("You are going down!!!");
            }
            else {
                if(input.equals("3")) {
                    System.out.println("You are going left!!!");
                }
                else {
                    if(input.equals("4")) {
                        System.out.println("You are going right!!!");
                    }
                    else{}
                }
            }
        }
    }
}

3 个答案:

答案 0 :(得分:3)

尝试切换案例http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

你的案子:

while(flag == false){

    switch (imput) {
        case "1":         
        System.out.println("You are going up!!!"); flag=true;
        break;

        case "2":  
        System.out.println("You are going down!!!"); flag = true;
        break;

        case "3":  
        System.out.println("You are going left!!!"); flag = true;
        break;

        case "4":   System.out.println("You are going right!!!"); flag = true;
        break;
    }

}

您可以设置可选条件default:

答案 1 :(得分:2)

你可以用while语句包装它......

while(!input.equals("1")
        && !input.equals("2")
        && !input.equals("3")
        && !input.equals("4"))
{
    input = keyboard.nextLine();
}

这表示在值不是1,2,3或4时继续获取输入。您还应该在while语句之前将输入初始化为某个随机值(值不同于1,2,3或者4)

答案 2 :(得分:2)

您可以在输入周围放置while循环,直到用户输入“退出”。像这样:

...
System.out.println("Your choice\n[1]Up \n[2]Down \n[3]Left \n[4]Right");
while (true) {
    input = keyboard.nextLine();
    if (input.equals("1")) {
        System.out.println("You are going up!!!");
    }
    else if(input.equals("2")) {
        System.out.println("You are going down!!!");
    }
    else if(input.equals("3")) {
        System.out.println("You are going left!!!");
    }
    else if(input.equals("4")) {
        System.out.println("You are going right!!!");
    }
        else if (input.equals("quit")) {
        break;
    }
        else {
            System.out.println("Incorrect input!");
        }
}