【问题标题】:Printing a private field from a separate class从单独的类打印私有字段
【发布时间】:2014-12-08 19:07:03
【问题描述】:

我的任务是将两个类联系在一起。第一类是售票机,它允许人们购买一张票,然后将其打印出来(通过 System.out.println)。第二类是显示时间的时钟显示。

我的任务是让票类打印时钟显示类中当前显示的时间。有人告诉我,我不需要编辑 NumberDisplay 类或 ClockDisplay 类。

我最初的想法是在我的 ticketmachine 类中创建一个新的 ClockDisplay 字段,然后使用

System.out.println("Time:" + ClockDisplay.displayString);

因为 displayString 是我用来在时钟显示类中查找值的。但是,由于该字段是私有的并且我不能编辑时钟显示类,所以我不能这样做。有什么想法吗?

谢谢。到目前为止,这是我的代码,前面提到的 TicketMachine 类中的代码。

数字显示

public class NumberDisplay
{
private int limit;
private int value;

/**
 * Constructor for objects of class NumberDisplay.
 * Set the limit at which the display rolls over.
 */
public NumberDisplay(int rollOverLimit)
{
    limit = rollOverLimit;
    value = 0;
}

/**
 * Return the current value.
 */
public int getValue()
{
    return value;
}

/**
 * Return the display value (that is, the current value as a two-digit
 * String. If the value is less than ten, it will be padded with a leading
 * zero).
 */
public String getDisplayValue()
{
    if(value < 10) {
        return "0" + value;
    }
    else {
        return "" + value;
    }
}

/**
 * Set the value of the display to the new specified value. If the new
 * value is less than zero or over the limit, do nothing.
 */
public void setValue(int replacementValue)
{
    if((replacementValue >= 0) && (replacementValue < limit)) {
        value = replacementValue;
    }
}

/**
 * Increment the display value by one, rolling over to zero if the
 * limit is reached.
 */
public void increment()
{
    if ((value +1) >= limit) {
        value = 0;
    }
    else {
        value = value + 1;
    }
}
}

时钟显示

public class ClockDisplay
{
private NumberDisplay hours;
private NumberDisplay minutes;
private NumberDisplay seconds;
private String displayString;    // simulates the actual display

/**
 * Constructor for ClockDisplay objects. This constructor 
 * creates a new clock set at 12:00:00.
 */
public ClockDisplay()
{
    hours = new NumberDisplay(12); // changed from 24hour to 12 hour
    minutes = new NumberDisplay(60);
    seconds = new NumberDisplay(60);
    updateDisplay();
}

/**
 * Constructor for ClockDisplay objects. This constructor
 * creates a new clock set at the time specified by the 
 * parameters.
 */
public ClockDisplay(int hour, int minute, int second)
{
    hours = new NumberDisplay(12); //changed from 24hour to 12 hour
    minutes = new NumberDisplay(60);
    seconds = new NumberDisplay(60);
    setTime(hour, minute, second);
}

/**
 * This method should get called once every minute - it makes
 * the clock display go one minute forward.
 */
public void timeTick()
{
    minutes.increment();
    if(minutes.getValue() == 0) {  // it just rolled over!
        hours.increment();
    }
    updateDisplay();
}

/**
 * Set the time of the display to the specified hour and
 * minute and second.
 */
public void setTime(int hour, int minute, int second)
{
    if (hour == 12) { //changing the display from '00:00' to '12:00'
        hour = 0;
    }
    hours.setValue(hour);
    minutes.setValue(minute);
    seconds.setValue(second);
    updateDisplay();
}

/**
 * Return the current time of this display in the format HH:MM:SS.
 */
public String getTime()
{
    return displayString;
}

/**
 * Update the internal string that represents the display.
 */
private void updateDisplay()
{
    int hour = hours.getValue(); //changes the display to from showing '00:00' to '12:00'
    if (hour == 0) {
        hour = 12;
    }
    displayString = hour + ":" + 
                    minutes.getDisplayValue() + ":" + seconds.getDisplayValue();
}

}

售票机

public class TicketMachine
{
// The price of a ticket from this machine.
private int price;
// The amount of money entered by a customer so far.
private int balance;
// The total amount of money collected by this machine.
private int total;
// The time from the clockdisplay class
private ClockDisplay time;

/**
 * Create a machine that issues tickets of the given price.
 */
public TicketMachine(int cost)
{
    price = cost;
    balance = 0;
    total = 0;
}

/**
 * @Return The price of a ticket.
 */
public int getPrice()
{
    return price;
}

/**
 * Return The amount of money already inserted for the
 * next ticket.
 */
public int getBalance()
{
    return balance;
}

/**
 * Receive an amount of money from a customer.
 * Check that the amount is sensible.
 */
public void insertMoney(int amount)
{
    if(amount > 0) {
        balance = balance + amount;
    }
    else {
        System.out.println("Use a positive amount rather than: " +
                           amount);
    }
}

/**
 * Print a ticket if enough money has been inserted, and
 * reduce the current balance by the ticket price. Print
 * an error message if more money is required.
 */
public void printTicket()
{
    if(balance >= price) {
        // Simulate the printing of a ticket.
        System.out.println("##################");
        System.out.println("# The BlueJ Line");
        System.out.println("# Ticket");
        System.out.println("# " + price + " cents.");
        System.out.println("##################");
        System.out.println();

        // Update the total collected with the price.
        total = total + price;
        // Reduce the balance by the prince.
        balance = balance - price;
        // Print the current time from the NumberDisplay class.
        System.out.println("Time:" + ClockDisplay.displayString);
    }
    else {
        System.out.println("You must insert at least: " +
                           (price - balance) + " more cents.");

    }
}

/**
 * Return the money in the balance.
 * The balance is cleared.
 */
public int refundBalance()
{
    int amountToRefund;
    amountToRefund = balance;
    balance = 0;
    return amountToRefund;
}

}

【问题讨论】:

    标签: java printing abstraction bluej modularization


    【解决方案1】:

    使用提供的方法getTime() 来获取它。喜欢,

    System.out.println("Time:" + ClockDisplay.getTime());
    

    另外(按照惯例),Java 变量应该以小写字母开头。

    ClockDisplay clockDisplay;
    // Set-up the variable....
    System.out.println("Time:" + clockDisplay.getTime());
    

    【讨论】:

    • 它说当我尝试这样做时,不能从静态上下文中引用非静态方法 getTime()?
    • 正确。您需要一个实例才能获取任何 non-static 字段。
    • 啊,是的。我已经在我的构造函数中实例化了 ClockDisplay 类,它现在可以工作了。感谢你的帮助。我也会更正我的变量。再次感谢
    【解决方案2】:

    如果您发现只有字段是私有的。要访问这些私有字段,您有公共的 getter-setter 方法。这是基本 OOP 概念之一 - 封装

    要访问您的 getter setter,您必须实例化您的对象,如您所见,这些不是静态方法。

    您可以在要打印时间的类中创建 ClockDisplay 对象。

    ClockDisplay clockDisplay = new ClockDisplay();
    System.out.print(clockDisplay.getTime());
    

    【讨论】:

      【解决方案3】:

      在您的 TicketMachine 类中,您忘记实例化 ClockDisplay。在TicketMachineprintTicket() 方法中试试这个:

      time = new ClockDisplay();        
      System.out.println("Time:" + time.getTime());
      

      更新

      以下是设置时间的方法:

      time = new ClockDisplay();
      time.setTime(3,9,34);
      System.out.println("Time: " + time.getTime());
      

      这是输出:

      ##################
      # The BlueJ Line
      # Ticket
      # -2 cents.
      ##################
      
      Time: 3:09:34
      

      【讨论】:

      • 天哪,多么愚蠢。令人惊讶的是,错过这样的事情是多么容易。现在工作正常,谢谢!编辑 - 事实上,它没有完全工作 - 无论我是否使用 setTime 方法更改时间,它都将时间显示为 12:00:00 - 这可能是什么原因?
      • 我以为你是从getTime() 方法中得到displayString 的?你还需要做什么?
      • 我不确定。我对代码所做的唯一修改是实现您告诉我放入 printTicket() 方法的那一行。
      • 你可以调用setTime(int hour, int minute, int second)方法来具体设置某个时间——像这样:time.setTime(2,43,13)然后调用time.getTime()打印。您能更具体地了解您要查找的内容吗?
      • 也许我解释得不够清楚,或者我只是傻了!在我的时钟显示类中,如果我使用 setTime 方法并将其设置为例如 11:11:11 然后去打印一张票,终端中返回的时间保持在 12:00:00 - 我希望它显示 11: 11:11 或我将其更改为的任何数字,我应该在我的其他课程中使用 setTime 方法。谢谢
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-11
      • 2017-02-14
      • 1970-01-01
      • 2020-03-28
      • 2023-03-28
      • 2018-12-28
      • 1970-01-01
      相关资源
      最近更新 更多