a12b23c34
a12b23c34

Reputation: 65

Why am I having trouble defining a double in an if statement?

My code looks like this:

if (gasQuality==87){
    double subtotal = unleaded * gallonsSold;
}else if (gasQuality==89){
    double subtotal = unleadedPlus * gallonsSold;
}else if (gasQuality==91){
    double subtotal = premium * gallonsSold;
}

but for some reason the compiler won't recognize 'subtotal' later on. For example if I wanted to apply a tax to the subtotal farther down the code, the compiler reads:

cannot find symbol
symbol  : variable subtotal
location: class Paniagua_Invoice
                final double cityTax = .0375 * subtotal;

What am I doing wrong?

Upvotes: 0

Views: 99

Answers (5)

Christian Tapia
Christian Tapia

Reputation: 34146

This is because of scoping. Variables exists inside the block they are declared in (there are also other rules, so you would like to read further on this). Since the first subTotal is declared in the if block (delimited by {}), you can only use it inside that block. To fix this you can try declaring subtotal before those if statements:

double subtotal = 0; // declaration and initialization

if (gasQuality==87) {
     subtotal = unleaded * gallonsSold; // don't declare again
}
else if (gasQuality==89)
     ...

Also, you could use a switch statement instead of those if-else if statements:

switch (gasQuality) {
    case 87:
        subtotal = ...;
        break;
    case 89:
        subtotal = ...;
        break;
    default:
        break;
}

Upvotes: 2

Cromax
Cromax

Reputation: 2052

You need to define subtotal outside of these blocks. It's scope is limited to space between { and }.

Upvotes: 0

Kumar Abhinav
Kumar Abhinav

Reputation: 6675

You need to define the double subtotal outside the if -else loop.Otherwise the scope of the variable ends in the fp-else loop.Try this:-

  double subtotal;

 if (gasQuality==87)
    {
            subtotal = unleaded * gallonsSold;
    }
    else if (gasQuality==89)
    {
            subtotal = unleadedPlus * gallonsSold;
    }
    else if (gasQuality==91)
    {
            subtotal = premium * gallonsSold;
    }

Upvotes: 1

nhgrif
nhgrif

Reputation: 62062

double subtotal;           

if (gasQuality==87) {
    subtotal = unleaded * gallonsSold;
} else if (gasQuality==89) {
    subtotal = unleadedPlus * gallonsSold;
} else if (gasQuality==91) {
    subtotal = premium * gallonsSold;
}

You have a variable scope problem. Refactoring your code to the above will allow you to use subtotal later in the method.

Upvotes: 0

La-comadreja
La-comadreja

Reputation: 5755

Declare the variable subtotal and set it to a preliminary value before the start of the if/else statement.

Upvotes: 0

Related Questions