代码之家  ›  专栏  ›  技术社区  ›  privilegedMale

switch语句中的扫描仪问题

  •  -1
  • privilegedMale  · 技术社区  · 7 年前

    我试图在一个方法中添加一个switch语句,然后将该方法放在另一个switch语句中。结果并不像我预料的那样。。。 当我执行程序时,控制台希望我立即添加一个用户输入,这不是我想要的。

    以下是我执行程序后控制台中显示的内容:

    qwerty公司

    你好,亲爱的朝圣者。你叫什么名字?

    上下快速移动

    你好,鲍勃。你准备好开始你的探索了吗?[是或否]

    请使用大写字母。。。[是或否]

    应用程序代码

    import java.util.Scanner;
    
    public class rolePlay {
    
        static Scanner player = new Scanner(System.in);
        static String system;
        static String choice = player.nextLine();
    
        public void letterError() {
            System.out.println("Please use capital letters...");
            System.out.println(system);
    
            switch (choice) {
    
            case "Yes" : System.out.println("May thine travels be shadowed upon by Talos...");
            break;
            case "No" : System.out.println("We shall wait for thee...");
            break;
            default: 
            break;
            }
        }
        public rolePlay() {
    
        }
    
        public static void main(String[] args) {
    
            rolePlay you = new rolePlay();
    
            System.out.println("Greetings, dear Pilgrim. What is thine name?");
            String charName = player.nextLine();
            System.out.println("Hello, " + charName + ". Is thou ready to start thine quest?");
    
            system = "[Yes or No]";
            System.out.println(system);
            //String choice = player.nextLine();
    
            switch (choice) {
    
            case "Yes" : System.out.println("May thine travels be shadowed upon by Talos...");
            break;
            case "No" : System.out.println("We shall wait for thee...");
            break;
            default : you.letterError();
            break;
            }
    
            player.close();
        }
    }
    
    2 回复  |  直到 7 年前
        1
  •  2
  •   Sean Van Gorder    7 年前
    static String choice = player.nextLine();
    

    当第一次访问该类时,此行将只调用一次。这就是为什么它需要用户立即输入。你需要打电话 player.nextLine() 在您想要获取用户输入的时候;在这种情况下,您应该在每个switch语句之前调用它,就像您注释掉的那行一样。

        2
  •  0
  •   Thatalent    7 年前

    使命感 player.nextLine() 并将其分配给静态变量 choice 导致问题。静态变量是在第一次调用类时检索的,在您的情况下,这意味着在调用main方法之前。您不应该为 选择 和分配 游戏者nextLine() 选择 当您希望用户向控制台输入某些内容时,在main方法内部。

        System.out.println("Greetings, dear Pilgrim. What is thine name?");
        String charName = player.nextLine();
        System.out.println("Hello, " + charName + ". Is thou ready to start thine quest?");
    
        system = "[Yes or No]";
        System.out.println(system);
        choice = player.nextLine();     
    

    移除后应该是这样的 游戏者nextLine() Static String choice 公告