0

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

3 Answers 3

7

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)

Sign up to request clarification or add additional context in comments.

2 Comments

even better, shouldn't be == or = at all.
Thanks alot! It did the trick ;) Maybe a little too late in the evening for me since I didn't see it, lol. I will accept the answer as soon as stackoverflow allows me :)
4

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) {

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.