gpt4 book ai didi

java - 我的代码无法输出汽车尺寸和总费用,我在试图找到问题时失去了理智

转载 作者:行者123 更新时间:2023-12-01 08:45:51 25 4
gpt4 key购买 nike

我有一项作业,并且我完成了它的代码,但问题仍然是,当我运行它时,汽车类型和总费用在最后显示为空白,这与继承有关,这对于继承来说是新的东西我和我希望我做对了。该计划分为 3 个独立的类(class),任何帮助将不胜感激

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);
}
}

最佳答案

在构造函数中设置值后,您永远不会计算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();

关于java - 我的代码无法输出汽车尺寸和总费用,我在试图找到问题时失去了理智,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43039336/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com