我有一个任务,我完成了我的代码,但问题仍然是Car类型和总费用在我运行时最后是空白的,它与继承有关,这是一个新的东西我,我希望我做得对。 该计划分为3个单独的课程,任何帮助将不胜感激
import java.util.*;
public class UseCarRental {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("How many days do you need the rental?");
int rentalLength = input.nextInt();
System.out.println("Enter requested car size:" +
"\nEconomy" + "\nMidsize" + "\nFullsize" + "\nLuxury");
String rentalCarSize = input.nextLine();
input.next();
CarRental firstRental = new CarRental(rentalLength, rentalCarSize);
firstRental.display();
}
}
class CarRental {
public String rentalCarSize = "";
public double rentalFeeDaily;
public int rentalLength = 0;
public double rentalFeeTotal= rentalFeeDaily*rentalLength;
public CarRental(int days, String carSize)
{
rentalCarSize = carSize;
rentalLength = days;
}
public void display()
{
System.out.println(
"#############" +
"\nCar Size = " + getRentalCarSize() +
"\nRental Length = " + rentalLength +
"\nTotal Fee = " + rentalFeeTotal
);
}
public void setRentalLength(int length)
{
rentalLength = length;
}
public String getRentalCarSize()
{
return rentalCarSize;
}
public int getRentalLength()
{
return rentalLength;
}
public double getRentalFeeTotal()
{
return rentalLength * rentalFeeDaily;
}
public double getRentalFeeDaily(String carSize)
{
switch (carSize)
{
case "Economy":
rentalFeeDaily = 29.99;
break;
case "Midsize":
rentalFeeDaily = 38.99;
break;
case "Fullsize":
rentalFeeDaily = 43.50;
break;
case "Luxury":
rentalFeeDaily = 79.99;
break;
}
return rentalFeeDaily;
}
}
import javax.swing.*;
public class LuxuryCarRental extends CarRental
{
public LuxuryCarRental(int days, String carSize)
{
super(days, carSize);
}
@Override
public void display()
{
JOptionPane.showMessageDialog(null,
"\nCar Size = " + getRentalCarSize() +
"\nRental Fee = " + rentalFeeDaily +
"\nRental Length = " + rentalLength +
"\nTotal Fee = " + rentalFeeTotal);
}
}
答案 0 :(得分:1)
在构造函数中设置值后,永远不会计算rentalFeeTotal
。将您的代码更改为:
class CarRental {
public String rentalCarSize = "";
public double rentalFeeDaily;
public int rentalLength = 0;
public double rentalFeeTotal = 0d;
public CarRental(int days, String carSize)
{
rentalCarSize = carSize;
rentalLength = days;
rentalFeeTotal = getRentalFeeDaily(carsize)*rentalLength;
}
您的代码中还有其他问题:
Scanner input = new Scanner(System.in);
System.out.println("How many days do you need the rental?");
int rentalLength = input.nextInt();
input.nextLine(); // ADD this line
System.out.println("Enter requested car size:" +
"\nEconomy" + "\nMidsize" + "\nFullsize" + "\nLuxury");
String rentalCarSize = input.nextLine();
input.next();