簡體   English   中英

int定義-不確定代碼的目的是什么

[英]int definition - not sure what the purpose is in the code

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“ price”。 這是我根據“ private int CalculationPrice” 3行得出的理解。 具有“整數價格=計算價格();”的目的是什么? 在公共場合無效? 我感覺自己在私有的“ calculatePrice”中定義了“ price”,現在我通過編寫“ int price = calculatePrice();”來重新定義“ price”。 令人困惑。 有人可以解釋為什么我的“ int price”被定義了兩次,這意味着在“ calculatePrice”中定義了,又在公共場合再次由“ calculatePrice”重新定義了?

我很難理解這個概念...感謝您的幫助!

在上面的代碼中,int price在兩個方法中定義了兩次,它們的范圍在它們定義的方法中大都結束了。 盡管代碼中的calculatePrice方法作用不大,但是在實際項目中,您可以分配一個復雜的方法,該方法執行大量邏輯並最終以int形式返回評估值。

您沒有重新定義可變價格。 兩個“價格”變量都在不同的范圍內,因此實際上它們不是同一變量。 在第一種情況下, price僅在submitOrder方法中可見並可以訪問,因為它是在該方法中聲明的。 在第二種情況下, price只能從calculatePrice方法中看到和訪問,因此即使名稱相同,它們也是完全不同的變量。

您可以在此鏈接中了解有關變量范圍和生存期的更多信息: http : //www.javawithus.com/tutorial/scope-and-lifetime-of-variables

順便說一句,我認為方法calculatePrice沒有正確定義,它需要一個int參數來設置數量:

private int calculatePrice(int quantity) {
    int price = quantity *5;
    return price;
}

修改此方法后,應以這種方式從方法submitOrder調用它:

 int price = calculatePrice("a number");

第二種方法:

private int calculatePrice() { int price = quantity *5; return price; } private int calculatePrice() { int price = quantity *5; return price; }這是一個返回整數類型的方法,它負責計算價格並返回價格結果。 在第一個方法中,您調用此函數並獲取價格結果,並將其存儲在實際變量中,該變量也稱為price。 為了避免混淆,您可以將第二種方法編寫為:

private int calculatePrice() { return quantity *5; } private int calculatePrice() { return quantity *5; } ,然后在第一個方法中將其調用為int price=calculatePrice()

calculatePrice()是一個返回整數值return price的函數。 因此,當您調用該函數時,它將在calculatePrice()執行該部分代碼,並將返回整數的答案。

在函數內部定義的變量int price的范圍僅限於該函數(您可以根據需要命名變量,不必僅命名“ price”)。

int price = calculatePrice(); 是另一個您要為其賦值的變量,該變量從函數返回。

修改變量名稱后的方法...

/**
 * Calculates the TOTAL price of the order.
 */
private int calculatePrice(int qty) {
    int totalPrice = quantity * qty;
    return totalPrice;
}

// You are calling by passing the quantity (qty)
int qty = 5;
int invoicePrice = calculatePrice(qty);
    String priceMessage = createOrderSummary(inoicePrice, hasWhippedCream);

希望這將有助於理解代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM