java - 循环中的 Switch 语句重复次数未知

标签 java arrays loops switch-statement do-while

嗨,我正在做一个小任务,我需要构建一个重复次数未知的循环。我的代码有一个问题,当用户输入字符时,输出会无限显示。我该如何解决这个问题?

String[] action = {"x", "u", "d", "l", "r", "s", "h", "e"}; 

        System.out.println("Please enter an action");

    String input = sc.next();

    char selection;

        do{
            selection = input.charAt(0);

        switch(selection){

            case 'x': System.out.print("Bye!"); 
                break;
            case 'u' : System.out.print("You go one square up.");
                break;
            case 'd': System.out.print("You go one square down.");
                break;
            case 'l': System.out.print("You go one square left.");
                break;  
            case 'r': System.out.print("You go one square right.");
                break;      
            case 's': System.out.print("You search the square for treasure. You find nothing.");
                break;  
            case 'h': System.out.print("You hide, waiting for enemies to come by. It gets boring after about an hour and a half, so you give up.");
                break;  
            case 'e': System.out.print("You eat some food. You regain 0 hit points");
                break;
            case 'z': 
                break;
            default: 
                System.out.println("I dont understand");
                break;
        }
        }
            while (selection != 'z');
        ```

最佳答案

sc.next() 暂停执行,直到用户进行输入。
但是,由于它位于循环之外,因此它不会停止读取新输入。
因此,您需要将 next() 调用移至循环中。

do{
  String input = sc.next();
  selection = input.charAt(0);

  switch(selection){
  // rest of the code

}

关于java - 循环中的 Switch 语句重复次数未知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61053313/

相关文章:

java - 在Matlab中逆向im2java?

java - Hibernate 5 创建 ID 未标记为 IDENTITY 的表

java - 在 Java 程序 GapContent$MarkData 中建立内存

c++ - 流到字节数组

Java XOR 两个数组

loops - 如何在 Airflow BashOperator 和 SSHOperator 中的 jinja 模板中传递循环和动态任务 ID

objective-c - 直到 Break 才结束的循环

java - 使用正则表达式从复杂字符串中获取项目

arrays - 处理输入数据时获取 "The second parameter of split is a string, not an array"

vb.net - SSIS 自定义脚本 : loop over columns to concatenate values