[英]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.