WilliamG
WilliamG

Reputation: 491

Converting fahrenheit to celcius (Java)

What I'm trying to do is to write a program that takes in a Fahrenheit value between 1-100 and convert it to Celsius. if the value isn't between the code should re-run without having to restart the program. I'm quite new to Java but this is what I have come up with.

package forstaPakage;
import javax.swing.*;

public class FTillC {

public static void main(String[] args) {

    int f = Integer.parseInt(JOptionPane.showInputDialog("hur många farenheit?"));
    do{
        if(f>0 && f<101){
            int c =  ((f-32)*5) / 9;
            System.out.println(f + " farhenheit är lika med " + c + " celcius" );
            break;
        }
        else{
            f = Integer.parseInt(JOptionPane.showInputDialog("Ogiltligt värde, skriv in ett nytt"));

        }
    }while(f>101 || f<1);

}
}

This code almost works. It does rerun if the "f" isn't between 1 and 100. if I then correct f the a acceptable value the Celsius value writes out "C" "infinity" times, the while loop for some reason doesn't break. If someone could explain what I have done wrong I would appreciate it.

Upvotes: 1

Views: 521

Answers (1)

PEF
PEF

Reputation: 207

I think you may want this instead, when I run the code you provided and enter 114 followed by 14, the program exits without displaying the conversion. Instead you could do the following:

package forstaPakage;

import javax.swing.*;

public class Main {

    public static void main(String[] args) {

        String str = "";

        while(true) {
            int f = Integer.parseInt(JOptionPane.showInputDialog( str + "\n" + "hur många farenheit?"));
            if(f>0 && f<101){
                int c =  ((f-32)*5) / 9;
                System.out.println(f + " farhenheit är lika med " + c + " celcius" );
                break;
            } else {
                str = "Ogiltligt värde, skriv in ett nytt";
            }
        }

    }
}

Upvotes: 1

Related Questions