-1
我真的很困惑。我需要这段代码来检查serial是否有值,如果不设置值则显示该消息。设置一个值并检查null是否不起作用
public class Calculator {
public static void main(String[] args) {
Product p2 = new Product("1st", 1.15);
p2.setSerial("1655");
System.out.println("done");
}
}
class Product {
private String name;
private String serial;
private double price;
public Product(String name, String serial, double price) {
this.name = name;
this.serial = serial;
this.price = price;
}
public Product(String name, double price) {
this.name = name;
serial = null;
this.price = price;
}
public void setSerial(String serial) {
if (serial == null)
this.serial = serial;
else
JOptionPane.showMessageDialog(null, "This item has a serial number");
}
public String getSerial() {
return serial;
}
}
使用调试器。如果您传入null,则只设置该值。你可能是指'if(this.serial == null)'。 –
请注意,您不应在setter中使用消息框。理想情况下,你根本不应该使用setter:只在构造函数中初始化它。但是如果你必须拥有setter,则抛出'IllegalStateException'。 –
您应该抛出异常而不是提出一个对话框,并让调用者决定如何处理它。 – Tezra