【问题标题】:While Loop with Switch Statement带 Switch 语句的 While 循环
【发布时间】:2015-03-31 15:40:08
【问题描述】:

在用户告诉程序停止之前,我无法让开关不断循环。 当提示用户输入 N 循环时,它们应该被送回开关的顶部

        char stop;
    while(stop == 'N'){
        switch(choice){
            case 1:
                System.out.println("Enter the time in seconds:");
                time = input.nextInt();
                displacement = (Math.pow(time,4)) + 16;
                System.out.println("Felix's displacement is equal to " + displacement + " meters");
                System.out.println("Stop the application(Y/N)");
                stop = input.findWithinHorizon(".",0).charAt(0);
                break;
            case 2:
                System.out.println("Enter the time in seconds:");
                time = input.nextInt();
                velocity = 4*(Math.pow(time,3));
                System.out.println("Felix's velocity is equal to " + velocity + " m/s");
                break;
            case 3:
                System.out.println("Enter the time in seconds:");
                time = input.nextInt();
                acceleration = 12*(Math.pow(time,2));
                System.out.println("Felix's acceleration is equal to " + acceleration + " m/(s*s)");
                break;
            default:
                System.out.println("Please select a choice");

        }            
    }
}

【问题讨论】:

  • 进入循环时stop的值是多少?它没有设置,因此它不会进入循环。选择发送到什么?您根本没有更新循环中的选择。
  • @StackFlowed:嗯,不仅如此 - 它不会编译......它不是绝对分配的。
  • 除此之外,如果choice 从未改变过,switch 内部循环的用途是什么,它将一次又一次地执行相同的情况

标签: java while-loop switch-statement


【解决方案1】:
  1. 粗略:初始化stop声明:

char stop = 'N';

  1. 更好:用 do while 循环替换您的 while

    做{

    } while (stop == 'N')

【讨论】:

    【解决方案2】:

    “stop”指的是内存中的空白空间,当您在第一次通过 while 循环时引用它时,它永远不会启动。您需要对其进行初始化或重新排列循环结构。此外,您似乎需要提示用户“选择”,除非该部分代码已被删除。

    【讨论】:

      猜你喜欢
      • 2018-09-16
      • 1970-01-01
      • 2021-03-08
      • 2015-12-23
      • 2013-12-20
      • 1970-01-01
      • 2023-04-10
      • 2013-05-17
      • 2013-04-13
      相关资源
      最近更新 更多