首页 > 解决方案 > 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”重新定义?

我很难理解这个概念......感谢您的帮助!

标签: javaandroid

解决方案


在参考上面的代码中, int price 在两个方法中定义了两次,其范围在它们定义的方法中非常结束。虽然你的代码中的 calculatePrice 方法做的不多,但在实际项目中,你可以分配一个复杂的方法来执行大量的逻辑,最后以 int 的形式返回评估值。


推荐阅读