而Loop with Switch Statement

时间:2015-03-31 15:40:09

标签: java while-loop switch-statement

我无法让开关一直循环直到用户告诉程序停止。 当用户提示输入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");

        }            
    }
}

2 个答案:

答案 0 :(得分:0)

  1. 粗略地说:在声明中初始化 stop
  2. char stop = 'N';

    1. 更好:将while替换为do while循环:

      做{

      } while(stop =='N')

答案 1 :(得分:0)

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