Question

I wrote this code in the main:

if (startAmount>0) //create new cashier object with or without a start amount
    Cashier newCashier = new Cashier(startAmount);
else Cashier newCashier = new Cashier();

and got an compile error for the second and third lines:

Multiple markers at this line
    - Cashier cannot be resolved to a variable
    - Syntax error on token "newCashier", delete

and:

Multiple markers at this line
    - Cashier cannot be resolved to a variable
    - Syntax error, insert "AssignmentOperator Expression" to complete 
     Assignment
    - Syntax error, insert ";" to complete Statement

but when i write the code like this with brackets:

if (startAmount>0)//create new cashier object with or without a start amount
{
    Cashier newCashier = new Cashier(startAmount);
}
else{ Cashier newCashier = new Cashier();}

it seems to be okay, no compile errors. can someone help me understand why?

Était-ce utile?

La solution

Why are you creating shadow variable for newCachier reference, you could rather do this

Cashier newCashier = null;
if (startAmount>0) //create new cashier object with or without a start amount
    newCashier = new Cashier(startAmount);
else 
     newCashier = new Cashier();

Autres conseils

It's always better to add those curly braces. Cause you won't forget to add them when you extend your code, which leads to strange behavior otherwise.

I think your exception of the first might came cause you forgot to put your else statement in a new line, but I am not sure.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top