开关语句中的扫描程序问题



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

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

键盘

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

鲍勃

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

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

应用程序代码

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();
    }
}
static String choice = player.nextLine();

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

调用player.nextLine()并将其分配给静态变量choice会导致问题。静态变量是在首次调用类时检索的,在您的情况下,这意味着在调用 main 方法之前。相反,当您期望用户向控制台输入内容时,不应将值分配给 choice 并将player.nextLine()分配给 main 方法内部的choice

    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();     

Static String choice声明中删除player.nextLine()后,应该看起来像这样。

最新更新