我不明白为什么我的代码没有注册对象上的最大大小。我可能认为这是因为底部变量可能会覆盖最小和最大值,但这似乎没有帮助
public class Shoes {
private static final int MIN_SIZE = 1;
private static final int MAX_SIZE = 15;
private String brand;
private double price;
private int size;
public Shoes(String brand, double price, int size) {
this.brand = brand;
this.price = price;
this.size = size;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
if (price < 0) {
System.out.println("Price Must be greater than zero!\n");
return;
}
this.price = price;
}
public int getSize() {
return size;
}
public void setSize(int size) {
if (size > MAX_SIZE && size < MIN_SIZE) {
System.out.println("Invalid Size!\n");
}
}
@Override
public String toString() {
return "Shoe [brand = " + brand + ", price = " + price + ", size = " + size + "]";
}
public static void main(String[] args) {
Shoes myShoes = new Shoes("J.F.", 45.99, 10);
Shoes otherShoes = new Shoes("Addidas", 65.99, 16);
System.out.println("The shoes: ");
System.out.println(myShoes.toString());
System.out.println("Other Shoes: ");
System.out.println(otherShoes.toString());
}
}其他鞋应该注册为无效的尺码。然而,它只是像往常一样运行代码,根本不输出无效大小的文本,我不明白为什么。
发布于 2017-08-02 03:59:59
正如我所看到的,在你的构造函数中,你没有使用"setSize“方法,而是直接将值从参数复制到"size”字段。因为该方法"setSize“没有触发,所以该方法中的验证没有发生。我建议你修改构造函数的代码,而不是直接设置"size“字段的值,你可以使用"setSize”方法,比如:
public Shoes(String brand, double price, int size) {
this.brand = brand;
this.price = price;
this.setSize(size);
}希望能有所帮助!
发布于 2017-08-02 03:57:02
您的问题是没有检查构造函数中的大小。您已经将其降级到一个单独的方法,该方法在对象初始化时不会被调用。
发布于 2017-08-02 03:57:18
您不会在构造函数中调用setSize方法。因此,不执行检查。
您可以简单地更改构造函数以使用该方法,如下所示:
public Shoes(String brand, double price, int size) {
this.brand = brand;
this.price = price;
setSize(size);
}https://stackoverflow.com/questions/45446569
复制相似问题