Reputation: 11
I'm learning java and was reading about methods in a text book. There is a program example to create a Celsius to Fahrenheit conversion table. I thought it would be a good idea to type into Eclipse and run the program. The program is below. Even thought it is exactly as the text in the book, I get the following error
c cannot be resolved to a variable
In the int f = (int) celsiusToFahrenheit
, and in println(c + "C = "
lines. It appears that c
is defined in the for loop as int so not sure what is wrong. Any assistance would be appreciated.
/*
* File: TermperatureConversionTable.java
* ---------------------
* This program creates a table of Celsius to Fahrenheit
* equivalents using a function to perform the conversion.
*/
import acm.program.*;
public class TemperatureConversionTable extends ConsoleProgram {
public void run() {
println("Celsius to Fahrenheit table.");
for (int c = LOWER_LIMIT; c <= UPPER_LIMIT; c += STEP_SIZE); {
int f = (int) celsiusToFahrenheit(c);
println(c + "C = " + f + "F");
}
}
/* Returns the Fahrenheit equivalent of the Celsius temperature c. */
private double celsiusToFahrenheit(double c) {
return 9.0 / 5.0 * c + 32;
}
/* Private constants*/
private static final int LOWER_LIMIT = 0;
private static final int UPPER_LIMIT = 100;
private static final int STEP_SIZE = 5;
}
Upvotes: 0
Views: 79
Reputation: 225
A small mistake at for
statement.
for (int c = LOWER_LIMIT; c <= UPPER_LIMIT; c += STEP_SIZE); {
int f = (int) celsiusToFahrenheit(c);
println(c + "C = " + f + "F");
}
Putting ;
before {
will terminate the loop without body and that's the cause of getting error as variable c
is not defined in the body.
Refer: The for statement
Upvotes: 1
Reputation: 28579
Your issue is with the for loop, which is never actually looped due to an extra semicolon.
for (int c = LOWER_LIMIT; c <= UPPER_LIMIT; c += STEP_SIZE); {
remove this ^
Because of the semicolon, you terminate the statement, the following braces will just change the scope of that block of code, which wherein c
is infact not defined.
Upvotes: 2
Reputation: 1571
Small syntactical error with a semicolon after the for-expression in your loop. Everything else looks fine to me.
for (int c = LOWER_LIMIT; c <= UPPER_LIMIT; c += STEP_SIZE); //<---remove the semicolon
{
int f = (int) celsiusToFahrenheit(c);
println(c + "C = " + f + "F");
}
Upvotes: 3