简体   繁体   English

带Switch语句的While循环

[英]While Loop with Switch Statement

I'm having trouble getting the switch to constantly loop until user tells the program to stop. 我无法让开关不断循环直到用户告诉程序停止为止。 When the user is prompt to put in a N to loop, they should be sent back to the top of the switch 当提示用户输入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");

        }            
    }
}
  1. Crudely: initialise stop on declaration: 粗略: 初始化 stop声明:

char stop = 'N';

  1. Better: replace your while with a do while loop: 更好:将您的while替换为do while循环:

    do { 做{

    } while (stop == 'N') } while(stop =='N')

"stop" refers to an empty space in memory when you refer to it at the first go through your while loop, so it will never start. 当您在第一次通过while循环引用它时,“停止”指的是内存中的空白空间,因此它将永远不会开始。 You'll need to initialize it or rearrange your looping structure. 您需要对其进行初始化或重新排列循环结构。 Additionally, it seems like you need to prompt the user for "choice", unless that portion of the code has been removed. 此外,似乎您需要提示用户“选择”,除非已删除该部分代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM