0

I wrote my Interface code already, but error. How can I compare two prices of two furniture objects? Am I doing it right in the if statements? The return statement says cannot find symbol. How can i fix this?

public boolean IsCheaper(Furniture f)
{
    if (f instanceof Furniture)
    {
         boolean status;
         if (price > f.getPrice())
             status = true;
         else if (price < f.getPrice())
             status = false;

    }
    return status;
}
Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268

2 Answers2

1
   public boolean IsCheaper(Furniture f)
    {
      boolean status= false; // or  true
      if (f instanceof Furniture) // if(f!=null) as suggested by a comment
       {

        if (price > f.getPrice())
            status = true;
        else if (price < f.getPrice())
            status = false;

       }
       return status;
     }

status should be declared outside if block since you need it outside.

Also is there really a need for if check, instanceof check is needed only if method is accepting a parent class of Furniture

Subin Sebastian
  • 10,870
  • 3
  • 37
  • 42
0

The scope of the variable boolean status; is just the if block if (f instanceof Furniture)

and you have a return statement outside that if block, so as soon as the if block is completed, variable status becomes unavailable as it becomes out of scope.

Therefore the compiler is not able to find it and hence says "cannot find symbol : status ".

So declare your status variable outside if (f instanceof Furniture) block.

Abubakkar
  • 15,488
  • 8
  • 55
  • 83
  • I did that before and it says Variable might not be initialized – Nicholai Hylton Dec 07 '12 at 04:22
  • just initaialize it to `true` or `false` when declaring it like `boolean status = false;` – Abubakkar Dec 07 '12 at 04:23
  • Are you talking like this @Abu?? public boolean IsCheaper(Furniture f) { boolean status = true; boolean status =false; if (f instanceof Furniture) { if (price > f.getPrice()) status = true; else if (price < f.getPrice()) status = false; } return status; – Nicholai Hylton Dec 07 '12 at 04:30
  • No just put `boolean status = true;` or `boolean status = false;` any one will do but not both as it will again say compiler error (two variables with same name) – Abubakkar Dec 07 '12 at 04:33