why my scripts is wrong, i have declare the cost..why i still got
error
// How much it cost for the gas to be consumed per cubic meter
import java.util.Scanner;
public class GasCharge
{
public static void main(String[] args)
{
// Declare constants and variables
double cost;
double gas;
// Read input
Scanner scn = new Scanner(System.in);
System.out.print("The amount of gas consumed in cubic
meters:");
gas = scn.nextDouble();
// Selection Structure
if (gas <= 100)
cost = 5.00;
else
if (gas <=300)
cost = gas * 0.4;
else
if (gas <= 500)
cost = gas * 0.2;
else
if (gas > 500)
cost = gas * 0.1;
// Display output (result)
System.out.println ("The total cost is($):" +cost);
}
}
ERROR->
GasCharge.java:32: variable cost might not have been initialized
System.out.println ("The total cost is($):" +cost);
^
1 error
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
Thanks in advance...=)
Tom Hawtin - 14 May 2007 11:13 GMT
> double cost;
> if (gas <=300)
> cost = gas * 0.4;
[quoted text clipped - 7 lines]
> // Display output (result)
> System.out.println ("The total cost is($):" +cost);
The definite assignment rules of the Java spec do not take into account
that a number is either less-than-or-equal or greater-than another[1].
You need an else clause (such as "else { throw new Error(); }").
As a matter of style I would always put braces in if-else statements.
The compiler doesn't take any notice of your indentation.
Also it's usual to put else and if on the same line, as:
if (a < b) {
...
} else if (a > b) {
...
} else if (a == b) {
...
} else {
throw new Error();
}
Tom Hawtin
[1] Actually a double can be a NaN (Not a Number) which is neither
greater, equal to or less than any number.
Patricia Shanahan - 14 May 2007 12:50 GMT
...
> if (gas <= 100)
> cost = 5.00;
[quoted text clipped - 7 lines]
> if (gas > 500)
> cost = gas * 0.1;
...
> ERROR->
> GasCharge.java:32: variable cost might not have been initialized
> System.out.println ("The total cost is($):" +cost);
> ^
> 1 error
You need to pick a value for cost before you attempt to use it.
Local variables are different from fields. Fields without an explicit
initializer get a default value, 0 for type double.
In deciding whether a variable is "definitely assigned", the compiler is
not permitted to combine conditions. Even if it were, if gas were a
Not-a-Number neither (gas <= 500) nor (gas > 500) would be true.
I would get rid of the last if, and make the final assignment the else
clause for the previous if.
Patricia