Angie Angie - 26 days ago 7
Java Question

Temperature conversion using objects in java

So i am currently writing a program using objects where the user enters an initial temperature, then the program has to compute it into celsius, which would just be the user input, then to fahrenheit and then to kelvin. The class also has a single constructor that accepts an initial temperature provided as a double argument. If this argument is < -273.15, set it to -273.15. I thought i was on the right track but when i compiled it, it wasn't doing what i wanted, any tips on how i can fix it?

With this code, the output gives me
Please enter the initial temperature: 20
The current temperature in Celsius is: 0.0
The current temperature in Fahrenheit is: 32.0
The current temperature in Kelvin is: 273.15
which isn't right... any tips?

//blueprint
public class TemperatureC{
private double temperatureC;

public TemperatureC(){
if(temperatureC<-273.15){
temperatureC = -273.15;}
else{}
}

public void setC(double c){
temperatureC = c;
}
public double getC(){return temperatureC;}
public double getF(){return (temperatureC * 1.8) + 32;}
public double getK(){return temperatureC + 273.15;}
}



//code
import java.util.Scanner;

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

TemperatureC temp = new TemperatureC();

double initialTemperature;
double celsius=temp.getC();
double fahrenheit=temp.getF();
double kelvin=temp.getK();

Scanner keyboard = new Scanner(System.in);

System.out.print("Please enter the initial temperature: ");
initialTemperature = keyboard.nextDouble();


//TemperatureC temp = new TemperatureC();

System.out.println("The current temperature in Celsius is: " + celsius);
System.out.println("The current temperature in Fahrenheit is: "+fahrenheit);
System.out.println("The current temperature in Kelvin is: "+kelvin);

}

}

Answer

You are assigning the values of celsius, fahrenheit, and kelvin before you know the temperature value. You want your tester to look more like this

public static void main(String[] args) {
  TemperatureC temp = new TemperatureC();
  double initialTemperature;
  Scanner keyboard = new Scanner(System.in);
  initialTemperature = keyboard.nextDouble();
  temp.setC(temp);

  System.out.println("The current temperature in Celsius is: " + temp.getC());
  System.out.println("The current temperature in Fahrenheit is: "+temp.getF());
  System.out.println("The current temperature in Kelvin is: "+temp.getK());
}

So the operations are now done after the temperature of initialTemperature is set.