gpt4 book ai didi

java - 错误无法应用于给定类型

转载 作者:行者123 更新时间:2023-12-01 23:26:00 25 4
gpt4 key购买 nike

代码:

public void checkHitDiscount(WineCase wineCase1)
{
if(hits%10==0)
{
wineCase1.setPrice()=0.9*wineCase1.getPrice;
System.out.println("Congratulations! You qualify for 10% discount.");
} else
System.out.println("You do not qualify for discount.");
}

我在这里得到的错误是:

Method setPrice cannot be applied to given types. required double, found no argument.

我正在尝试修改 WineCase 类中的 price 字段。这是双。

最佳答案

setPrice() 是一种方法。您似乎还有一个名为 getPrice() 的方法,并且这些方法可能都对应于对象中名为 price 的实例变量。

如果 priceprivate,那么您可以这样调用 getPrice():

wineCase1.getPrice();

这将返回一个 double(假设 price 的类型为 double)。

同样,如果 priceprivate,那么您需要将其设置如下:

wineCase1.setPrice(somePrice);

因此,在上面的示例中,如果您想将 price 设置为当前价格的 90%,正确的语法如下所示:

wineCase1.setPrice(0.9*wineCase1.getPrice());
<小时/>

或者,您也可以为此类编写一个 public 方法,如下所示:

public void discountBy(double disc) {
price *= 1.0 - disc;
}
// or like this:
public void discountTo(double disc) {
price *= disc;
}
// or both...

要使用此方法并对 wineCase1 应用 10% 的折扣,您需要执行以下操作:

wineCase1.discountBy(0.1);
// or like this:
wineCase1.discountTo(0.9);

那么你仍然会使用:

wineCase1.getPrice();

从对象中检索私有(private)变量 price

<小时/>

最后,这可能是最好的解决方案,添加这些方法:

public double getPriceDiscountedBy(double disc) {
return price*(1.0-disc);
}

public double getPriceDiscountedTo(double disc) {
return price*disc;
}

这些方法将允许您检索折扣价的值,而无需更改商品的原始价格。这些将在您获得 getPrice 的同一位置调用,但采用折扣参数来仅修改返回的价格。例如:

double discountedPriceOutsideOfObject = wineCase1.getPriceDiscountedTo(0.9);
//or like this:
double discountedPriceOutsideOfObject = wineCase1.getPriceDiscountedBy(0.1);

关于java - 错误无法应用于给定类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19961087/

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