You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在DiscountTicket类中初始化字符串变量并实现指定toString方法

解决方案

1. 添加折扣类型成员变量

在DiscountTicket类中新增私有成员变量,用来存储构造参数传入的学生/老人类型标识:

private String discountType;

2. 修正构造方法

在构造方法中给新成员变量赋值,同时移除冗余的super.daysInAdvance = days;(父类构造器super(days)已经完成这个赋值操作):

public DiscountTicket(int days, String s) {
    super(days);
    this.discountType = s; // 存储传入的类型字符串
    getPrice(); // 触发价格计算
}

3. 实现toString方法

按照要求的输出格式编写toString方法,注意使用父类的number属性(假设父类Ticket中number为protected权限;如果父类提供了getNumber()方法,就替换为getNumber()),并用currencyF格式化价格:

public String toString() {
    return String.format("Ticket: [ serial#: %d Price: %s Type: %s]", 
                         super.number, 
                         currencyF.format(super.price), 
                         discountType);
}

4. 优化getPrice方法(可选)

把原方法中的两个独立if改成if-else结构,减少不必要的判断逻辑:

@Override
public double getPrice() {
    if (super.daysInAdvance >= 10) {
        super.price = 15;
    } else if (super.daysInAdvance >= 1) {
        super.price = 20;
    }
    return super.price;
}

完整的DiscountTicket类代码

import java.text.DecimalFormat;

public class DiscountTicket extends Ticket { // 假设继承自Ticket类
    // For formatting currency
    DecimalFormat currencyF = new DecimalFormat("#.00");
    private String discountType;

    // parameter constructor
    public DiscountTicket(int days, String s) {
        super(days);
        this.discountType = s;
        getPrice();
    }

    // override getPrice()
    @Override
    public double getPrice() {
        if (super.daysInAdvance >= 10) {
            super.price = 15;
        } else if (super.daysInAdvance >= 1) {
            super.price = 20;
        }
        return super.price;
    }

    @Override
    public String toString() {
        return String.format("Ticket: [ serial#: %d Price: %s Type: %s]",
                super.number,
                currencyF.format(super.price),
                discountType);
    }
}

运行测试类后,就能得到你需要的输出格式:

Ticket: [ serial#: 3 Price: 20.00 Type: Student]
Ticket: [ serial#: 4 Price: 15.00 Type: Senior]

内容的提问来源于stack exchange,提问作者M_DS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 07:13:14