简体   繁体   中英

Getting out of while-loop with switch-statement

I was trying to make a program which reads your temperature, gives you a feedback as to how good it is, above, under or inbetween the average bodytemperature. After this I want the program to ask the user whether he/she wants to do another reading, by input. For this I use a switch-statement. It almost works fine: the user input y, the program loops again and all is jolly good. However, when the user input n, the program still restarts? Can anyone help me as to why this is happening?

The code:

    import java.util.*;

class Uke2Ekstra17{
    public static void main(String[]args){

    Scanner input=new Scanner(System.in);
    boolean lokke=true;


    while(lokke=true){
        System.out.println("Vennligst oppgi temperaturen din, så skal du få vite om du ligger over, under eller innenfor gjennomsnittstemperaturen! Skriv her: ");
        double temp=input.nextDouble();

        if(temp<36.5){
        System.out.println("Du ligger under gjennomsnittet med " + (36.5-temp) + " grader.");
        }else if(temp>36.5 && temp<37.5){
        System.out.println("Du ligger innenfor gjennomsnittstemperaturen.");
        }else{
        System.out.println("Du ligger over gjennomsnittet med " + (temp-37.5) + " grader.");
        }
        System.out.println("Vil du gjøre en ny maaling? y/n: ");

        char svar=input.next().charAt(0);

        switch(svar){

        case 'y': 
        lokke=true;
        break;
        case 'n':
        lokke=false;
        break;
        }
    }
    }
}

Your boolean while (lokke=true) is assigning lokke , not checking it. It should be a == . If you're checking a boolean though, you don't need to compare it to true or false explicitly. You can use while (lokke)

This statement

while (lokke=true) {

always evaluates to true as assignments always evaluate to their right hand side value. Instead use

while(lokke == true) {

or simply

while (lokke) {

Another option would be create an infinite loop, and break it, so you wouldn't even need lokke variable.-

while(true) {
    //...
    if (svar == 'n') {
        break;
    }
}

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