如果数量不是正数,则应将其设置为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
答案 0 :(得分:1)
您正在分配:
this.partQuantity = 0;
但你回来了:
return partPrice * partQuantity;
(传递给方法的参数)。
你可以通过返回来修复它:
return this.partPrice * this.partQuantity;
你真的不应该将任何参数传递给这个方法。
答案 1 :(得分:0)
这就是你需要的。
public double invoiceAmountMethod(double partPrice, int partQuantity) {
return (partQuantity < 0 || partPrice < 0.0)?0.0:partPrice * partQuantity;
}