2014-12-08 3 views
-1

Мне было поручено связать два класса вместе. Первый класс - это билетная машина, которая позволяет человеку купить билет, а затем распечатать его (через System.out.println). Второй класс - это дисплей часов, который отображает время.Печать частного поля из отдельного класса

Моя задача - сделать класс билета печати временем, отображаемым в настоящее время в классе отображения часов. Мне сказали, что мне не нужно редактировать класс NumberDisplay или класс ClockDisplay.

Моего initital мысли создать новое поле ClockDisplay в моем классе ticketmachine, а затем использовать

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

в DisplayString, что я использую, чтобы найти значение в пределах класса clockdisplay. Однако, поскольку поле является частным, и я не могу редактировать класс clockdisplay, я не могу этого сделать. Есть предположения?

спасибо. Вот мой код до сих пор, с вышеупомянутым фрагментом кода в классе TicketMachine.

NumberDisplay

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

ClockDisplay

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

}

машина Ticket

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

}

ответ

0

Используйте предоставленный метод getTime(), чтобы получить его. Например,

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

Также (по соглашению) переменные Java должны начинаться с строчной буквы.

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

В нем говорится, что нестатический метод getTime() не может ссылаться на статический контекст, когда я пытаюсь это сделать? – user3455584

+0

Исправить. Вам нужен экземпляр, чтобы получить любое поле [нестатический] (http://stackoverflow.com/a/20592547/2970947). –

+0

Ах да. Я создал экземпляр класса ClockDisplay в своем конструкторе, и теперь он работает. Спасибо за вашу помощь. Я также исправлю свои переменные. Еще раз спасибо – user3455584

0

В вашем TicketMachine классе, вы забыли экземпляр ClockDisplay. Попробуйте это в методе printTicket() в TicketMachine:

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

UPDATE

Вот как вы можете установить время:

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

Вот результат:

################## 
# The BlueJ Line 
# Ticket 
# -2 cents. 
################## 

Time: 3:09:34 
+0

Гоша, как глупо. Удивительно, как легко пропустить что-то подобное. Он работает отлично, спасибо! Редактировать - infact, он не работает полностью - он отображает время как 12:00:00 независимо от того, изменяю ли я время с помощью метода setTime - что может быть причиной этого? – user3455584

+0

Нет проблем! Пожалуйста, отметьте это как принятый ответ :) – cno

+0

Отметьте мое редактирование! Не совсем там, на самом деле :( – user3455584

0

Если вы заметили только поле, частный. Чтобы получить доступ к этим частным полям, у вас есть общедоступные методы getter-setter. Это одна из основных концепций ООП - Инкапсуляция.

Чтобы получить доступ к вашему сетевому устройству, вам необходимо создать экземпляр объекта, как вы можете видеть, это не статические методы.

Вы можете создать объект ClockDisplay в классе, где вы хотите напечатать время.

ClockDisplay clockDisplay = new ClockDisplay(); 
System.out.print(clockDisplay.getTime()); 
Смежные вопросы