java - int 定义 - 不确定代码中的目的是什么
问题描述
public void submitOrder(View view) {
CheckBox whippedCreamCheckBox = (CheckBox) findViewById(R.id.whippedCreamCheckBox);
boolean hasWhippedCream = whippedCreamCheckBox.isChecked();
Log.v("MainActivity", "Has whipped Cream: " + hasWhippedCream);
int price = calculatePrice();
String priceMessage = createOrderSummary(price, hasWhippedCream);
displayMessage(priceMessage);
}
/**
* Calculates the price of the order.
*
* @param 'quantity' is the number of cups of coffee ordered
* "5" is used for the price of each coffee
* @return total price
*/
private int calculatePrice() {
int price = quantity *5;
return price;
}
我对编码很陌生,所以请记住这是新事物,我正在尝试了解它是如何工作的。我正在学习这门课程,最终得到了上面的代码。
我在质疑为什么我有“calculatePrice”int,因为我所需要的只是由数量定义并存储价格值的int“价格”。这就是我根据“private int calculatePrice” 3 行所理解的。拥有“int price = calculatePrice();”的目的是什么?在公共空间?我觉得我在私有“calculatePrice”中定义了“价格”,现在我正在通过编写“int price = calculatePrice();”来重新定义“价格”。这很令人困惑。有人可以解释为什么我“int price”被定义了两次,意思是在“calculatePrice”中定义并在公共无效中再次由“calculatePrice”重新定义?
我很难理解这个概念......感谢您的帮助!
解决方案
在参考上面的代码中, int price 在两个方法中定义了两次,其范围在它们定义的方法中非常结束。虽然你的代码中的 calculatePrice 方法做的不多,但在实际项目中,你可以分配一个复杂的方法来执行大量的逻辑,最后以 int 的形式返回评估值。
推荐阅读
- java - 修复:我已将 sinch jar 文件添加到 libs 文件夹并作为 android studio 中的库,但是当我导入 sinch 或相关类时,它不显示导入选项
- google-apps-script - Google App Script MailApp 停止发送电子邮件
- flutter - 如何使用 2 个流,其中流 2 取决于流 1?
- python - 如何将多个json记录放入mongoDB?
- c# - 从 Windows 窗体打开网页 (HTML)
- python - 如何比较每个数据框不同大小的值并返回字符串
- python - python中的ValueError:int和float都不起作用
- java - Swagger Editor 为 Rest 端点创建错误的路径
- mongodb - 是否可以在 spring mongodb 存储库中为 @Query 方法提供默认值?
- javascript - 卡住创建表动态添加行