简体   繁体   中英

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

        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:

char stop = 'N';

  1. Better: replace your while with a do while loop:

    do {

    } 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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