晚上好!
我认为这里有一些我不了解的继承或JOptionPane,但基本上我想弄清楚如何在LuxuryCarRental子类中实际使用新的JOptionPane。
目前,如果选择为“l”,则显示2个对话框,父类中的一个框和我在子类中添加的新框。理想情况下,我只想要一个对话框。我认为这是我可以在没有JOptionPane的情况下做的事情,但如果可能的话我想尝试使用JOptionPane。
我的代码:
CarRental.java(父类)
import javax.swing.JOptionPane;
public class CarRental
{
private String name;
private String zipCode;
private String size;
private double dailyFee;
private int rentalDays;
private double totalFee;
public CarRental(String name, String zipCode, String size, int rentalDays)
{
this.name = name;
this.zipCode = zipCode;
this.size = size;
if (size.equals("e"))
{
dailyFee = 29.99;
}
else if (size.equals("m"))
{
dailyFee = 38.99;
}
else if (size.equals("f"))
{
dailyFee = 43.50;
}
this.rentalDays = rentalDays;
totalFee = dailyFee * rentalDays;
}
public void display()
{
JOptionPane.showMessageDialog(null, "Car for " + name + " from zip code " + zipCode + "\n"
+ "Type = " + size + "\n"
+ "Daily Fee = " + dailyFee + "\n"
+ "Days = " + rentalDays + "\n"
+ "Your rental is $" + totalFee);
}
//includes getters and setters but I didn't include this in this post
LuxuryCarRental.java(子类)
import javax.swing.JOptionPane;
public class LuxuryCarRental extends CarRental
{
public LuxuryCarRental(String name, String zipCode, String size, int rentalDays)
{
super(name, zipCode, size, rentalDays);
if (size.equals("l"))
{
this.setDailyFee(79.99);
String includeChauffeur;
includeChauffeur = JOptionPane.showInputDialog(null, "Include chauffeur? Y/N");
if (includeChauffeur.equals("Y") || includeChauffeur.equals("y"))
{
this.setDailyFee(279.99);
this.setTotalFee(this.getDailyFee()*this.getRentalDays());
JOptionPane.showMessageDialog(null, "Chauffeur @ $200/day = $" + 200 * this.getRentalDays());
}
}
}
}
UserCarRental.java(驱动程序类)
import javax.swing.JOptionPane;
public class UseCarRental
{
public static void main(String[] args)
{
String name = JOptionPane.showInputDialog("Enter name");
String zip = JOptionPane.showInputDialog("Enter zip code");
String size = JOptionPane.showInputDialog("Enter type of car" + "\n" + "e - economy" + "\n" + "m - midsize" + "\n" + "f - full" + "\n" + "l - luxury");
int days = Integer.parseInt(JOptionPane.showInputDialog("Enter days to rent"));
CarRental userInfo = new LuxuryCarRental(name, zip, size, days);
userInfo.display();
}
}
非常感谢任何帮助!
答案 0 :(得分:2)
我认为这里的教训是不要将UI代码与模型代码混合在一起。了解您的CarRental类及其所有子类是逻辑类或模型类,并且可以将其视为模拟物理或逻辑现实的类。它们应该以这种能力使用,并且应该写入,以便将信息传递给它们并从中提取出来,但它们不应直接与用户交互。相反,这是UI(用户界面)类的责任,在这里它非常简单,只有你的主要方法。因此,我建议您从CarRental和LuxeryCarRental中调用JOptionPane调用,然后在从CarRental对象中提取状态后,在main方法中显示JOptionPane。
否则,如果您绝对必须让模型类显示其信息,那么请在可以完全覆盖的方法中执行。实际上,您可以让您的子类覆盖display()
方法,然后在那里打印出它的数据。