user9409576
user9409576

Reputation:

Difficulty with a loop in the main that makes a calls to a method (Temperature Conversions)

I am trying to write a method that takes in a Fahrenheit temperature and returns the equivalent Celsius temperature. To do this, I have been tasked with writing a loop in the main that makes calls to a method and prints the conversions for Fahrenheit values: 0, 5, 10, 15, …, 100.

Here is what I have:

import java.util.Scanner;

public class TemperatureConverter {

    public static void main(String[] args) {
        int F;
        F = 0;
        double tempCelsius;

        while (F <= 100) {
            convert(F);
            System.out.println(F + " degrees F corresponds to " + tempCelsius + " degrees C");
            F = F + 5;
        }
    }

    public static double convert(int F) {
        tempCelsius = ((5.0 / 9.0) * (F - 32));

        return tempCelsius;
    }
}

And the error I get is

/TemperatureConverter.java:32: error: cannot find symbol
tempCelsius = ((5.0 / 9.0) * (F - 32));
^

I appreciate any direction.

Upvotes: 0

Views: 57

Answers (4)

Anubhav Gupta
Anubhav Gupta

Reputation: 102

Update below statement in while loop and see it running

This:

convert(F);

With:

tempCelsius = convert(F);

Upvotes: 0

Aeron Storm
Aeron Storm

Reputation: 119

The declaration double tempCelsius;in the main method does not have a valid scope in the convert method. So you will have to declare it again inside the convert method too.Once you do that, you will have to store the value returned from convert method to the tempCelsius variable in main method inorder to print it.In simple words the tempCelsius you have declared in main method has nothing to do with the tempCelsius in the convert method as they both have different scopes.

Upvotes: 0

pritam parab
pritam parab

Reputation: 85

You declared variable tempCelsius in main method, so it not known by convert method. There are 2 solution:

  1. Declare tempCelsius outside the main method.

OR

  1. Don't use tempCelsius variable in convert mathod, instead directly return calculated value. Eg.return(logic to convert Fahrenheit to Celsius)

Upvotes: 0

luk2302
luk2302

Reputation: 57124

Your function should be

public static double convert(int F) {
    return ((5.0 / 9.0) * ( F - 32 ));
}

And you should call it via:

tempCelsius = convert(F);

Previously you were trying to access the local variable tempCelsius from convert but the variable is only available inside main.

Upvotes: 1

Related Questions