gpt4 book ai didi

java - 我的 java 类验证不起作用,为什么?

转载 作者:行者123 更新时间:2023-12-01 09:57:15 24 4
gpt4 key购买 nike

如果数量不是正数,则应设置为 0。如果每件商品的价格不是正数,则应设置为 0.0。然而,当我输入负数时,它会继续将我的变量设置为负而不是零。

这是我的类包 com.company;

/**
* Created by juliodiaz on 5/7/16.
*/
public class Invoice {

private String partNumber;
private String partDescription;
private int partQuantity;
private double partPrice;

public Invoice(String partNumber, String partDescription, int partQuantity, double partPrice) {
this.partNumber = partNumber;
this.partDescription = partDescription;
this.partQuantity = partQuantity;
this.partPrice = partPrice;
}

public String getPartNumber() {
return partNumber;
}

public void setPartNumber(String partNumber) {
this.partNumber = partNumber;
}

public String getPartDescription() {
return partDescription;
}

public void setPartDescription(String partDescription) {
this.partDescription = partDescription;
}

public int getPartQuantity() {
return partQuantity;
}

public void setPartQuantity(int partQuantity) {
this.partQuantity = partQuantity;
}

public double getPartPrice() {
return partPrice;
}

public void setPartPrice(double partPrice) {
this.partPrice = partPrice;
}

public double invoiceAmountMethod(double partPrice, int partQuantity) {
if (partQuantity < 0 || partPrice < 0.0) {
this.partQuantity = 0;
return partPrice * partQuantity;
}
else
return partPrice * partQuantity;
}
}

//Main method
package com.company;

public class Main {

public static void main(String[] args) {
// write your code here

Invoice myTruck = new Invoice("A101", "Wheels", -2, 100.00);

System.out.println(myTruck.getPartDescription());
System.out.println(myTruck.getPartNumber());
System.out.println(myTruck.getPartQuantity());
System.out.println(myTruck.getPartPrice());

double price = myTruck.getPartPrice();
int quantity = myTruck.getPartQuantity();

System.out.println("The total cost is " + myTruck.invoiceAmountMethod(price, quantity));

}
}

输出

Wheels
A101
-2
100.0
The total cost is -200.0

最佳答案

您正在分配:

this.partQuantity = 0;

但你返回:

return partPrice * partQuantity;

(传递给方法的参数)。

您可以通过返回来修复它:

return this.partPrice * this.partQuantity;

并且您确实不应该向此方法传递任何参数。

关于java - 我的 java 类验证不起作用,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37095456/

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