简体   繁体   English

在Java中创建新对象错误

[英]Creating new object in java error

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? 有人可以帮助我理解为什么吗?

Why are you creating shadow variable for newCachier reference, you could rather do this 为什么要为newCachier参考创建阴影变量,您宁愿这样做

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

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. 我认为您可能会遇到第一个例外,因为您忘记将else语句放在新的一行,但是我不确定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM