1

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.

Andrew Thompson
  • 163,965
  • 36
  • 203
  • 405
WilliamG
  • 301
  • 1
  • 4
  • 15
  • 1
    can't see what's the problem. But can you clarify "if i then correct f the a acceptable value the Celsius"? – Gaur93 Sep 23 '16 at 12:11
  • 1
    Works fine here (add a System.out with some message after the while, and the message will be printed after you enter a legal value.) Thus, something must different between the test code you posted and the real problem. – mtj Sep 23 '16 at 12:16
  • if i first run the code and enter a value that isn't between the span 1-100 the code re-runs and the message "invalid value, write a new one" pops up. if i then write a value between 1-100 the value gets written out "infinite times" – WilliamG Sep 23 '16 at 12:17

1 Answers1

1

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

    }
}
PEF
  • 207
  • 1
  • 5
  • 11
  • I can see why this is simpler even though i dont quite understand what this do "String str = "";" and how it works in the else-statment, why does a new dialog-box shpow up just because you write "str". If you mind to explain it i would deeply appriciateit. – WilliamG Sep 23 '16 at 13:10