Ricky
Ricky

Reputation: 133

Class member in java and assignment

Below is my program which i have doubts about:

    import java.util.Scanner;

    class degrees
    {
    float faren;
    //float cel = (faren-32)*0.55f; doesn work
    void conversion()
    {
        System.out.println("Fahrenheit is "+(faren-32)*0.55f+"Celcius");
        //System.out.println("Fahrenheit is "+cel+"Celcius"); doesnt work
    }
    }

    class Problem4 
    {
    public static void main(String args[])
    {
        degrees deg = new degrees();
        System.out.println("Enter the temperature in Fahrenheit");
        try(Scanner n1 = new Scanner(System.in))
        {
            deg.faren = n1.nextFloat();
        }
        deg.conversion();
    }
   }

So the two statements that i have made comments

  float cel = (faren-32)*0.55f;// this one and 
  System.out.println("Fahrenheit is "+cel+"Celcius");//this one

Both the above statement does not work. I m assigning the value of faren by calling object but still. Can anybody explain me why?

Its just a simple program so please don't correct the mistakes if any. I need to figure out myself. Just help me with the above two statement guys.

Upvotes: 0

Views: 129

Answers (2)

Nikos M.
Nikos M.

Reputation: 8325

use this instead:

class degrees
    {
    float faren = 0;
    float cel = 0;

    void degrees(float faren)
    {
       this.faren = faren;
       this.cel = (this.faren-32)*5.0f/9.0f;
    }
    void conversion()
    {
        //System.out.println("Fahrenheit is "+(this.faren-32)*0.55f+"Celcius");
        System.out.println("Fahrenheit is "+this.cel+"Celcius");
    }
    }

use like this:

var deg = new degrees(farheneitValueHere);
deg.conversion();

this float cel = (faren-32)*0.55f; does not work because you cannot initialise a property when defined with an expression (especially an expression which includes another property). this System.out.println("Fahrenheit is "+cel+"Celcius"); does not work similarly because cel has not been defined/converted (by 1st reason). Initialise the values in the constructor instead (as in the example above)

Upvotes: 1

rgettman
rgettman

Reputation: 178253

It looks like you are attempting to convert faren from Fahrenheit to Celsius before faren is given a value. Java will initialize class variables to 0 if not given a value, so cel will be given the Celsius equivalent of 0 Fahrenheit. The reason you get -17.6 is that's the result of (0 - 32) * 0.55f.

Instead of using class variables, have your conversion method take a parameter in degrees Fahrenheit, do the math in the method, and then return the Celsius value.

Also, conversion isn't very descriptive of the purpose. You may want to rename the method fahrenheitToCelsius or something similar.

For accuracy you should to multiply by 5.0f/9.0f instead of 0.55f.

Upvotes: 1

Related Questions