gpt4 book ai didi

java - 在java错误中创建新对象

转载 作者:行者123 更新时间:2023-11-30 08:24:42 25 4
gpt4 key购买 nike

我主要写了这段代码:

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

第二行和第三行出现编译错误:

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

和:

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

但是当我用括号写这样的代码时:

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

好像没问题,没有编译错误。谁能帮我理解为什么?

最佳答案

为什么要为 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();

关于java - 在java错误中创建新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22763986/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com