I have quickly made a small program that converts Fahrenheit into Celsius and Celsius into Fahrenheit but when I try to use the one variable it doesn't do all of the steps. I can understand why but I cannot figure out how I can prevent it from only doing the last operation because I want it to do all of the operations in order.
As far as im aware if I use the same variable for all of the operations such as the -32, *5 and /9 it will only do the last one because I have used =
to assign that as the value but I am unsure whether this is the reason or not, any help would be appreciated, thanks.
public class TempConversion{
//FahrenheitSteps
private int Fahrenheit;
private int FahrenheitA;
private int FahrenheitB;
private int FahrenheitC;
//CelciusSteps
private int Celcius;
private int CelciusA;
private int CelciusB;
private int CelciusC;
//Constructor
public TempConversion(){
Fahrenheit = 0;
Celcius = 0;
}
//Convert Fahrenheit to celcius
public void FahrenheitToCelcius(int Fahren){
CelciusA = Fahren - 32;
CelciusB = CelciusA * 5;
CelciusC = CelciusB / 9;
System.out.println(CelciusC + " Is the celcius equivalent");
}
//Convert Celcius to fahrenheit
public void CelciusToFahrenheit(int Celc){
FahrenheitA = Celc * 9;
FahrenheitB = FahrenheitA / 5;
FahrenheitC = FahrenheitB + 32;
System.out.println(FahrenheitC + " Is the fahrenheit equivalent");
}
}
You can use an example like this https://www.programmingsimplified.com/java/source-code/java-program-to-convert-fahrenheit-to-celsius
And replace Scanner
with your value.
import java.util.*;
class FahrenheitToCelsius {
public static void main(String[] args) {
float temperature;
Scanner in = new Scanner(System.in);
System.out.println("Enter temperature in Fahrenheit");
temperature = in.nextInt();
temperature = ((temperature - 32)*5)/9;
System.out.println("temperature in Celsius = " + temperature);
}
}
You can combine the following three lines:
CelciusA = Fahren - 32;
CelciusB = CelciusA * 5;
CelciusC = CelciusB / 9;
into
Celcius = (Fahren-32) * 5 / 9;
The same thing can be done for your celciusToFahrenheit method. There shouldn't be an issue performing multiple math operations on one line as long as you remember the order of operations.
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.