import java.text.NumberFormat;
// 1. ***** indicate that SavingsAccount inherits
// from BankAccount
public class SavingsAccount
{
public final double DEFAULT_RATE = .03;
// 2. ****** define the private interestRate instance variable
// interestRate, a double, represents an annual rate
// Part 2 student code starts here:
private double interestRate;
// Part 2 student code ends here.
// 3 ***** write the default constructor
/** default constructor
* explicitly calls the BankAccount default constructor
* set interestRate to default value DEFAULT_RATE
* print a message to System.out indicating that
* constructor is called
*/
// Part 3 student code starts here:
public void BankAccount()
{
interestRate = DEFAULT_RATE;
System.out.println("Default constructor is called. ");
}
// Part 3 student code ends here.
// 4 ***** write the overloaded constructor
/** overloaded constructor
* explicitly call BankAccount overloaded constructor
* call setInterestRate method, passing startInterestRate
* print a message to System.out indicating that
* constructor is called
* @param startBalance starting balance
* @param startInterestRate starting interest rate
*/
// Part 4 student code starts here:
public void BankAccount(double startBalance,double startInterestRate)
{
setInterestRate(startInterestRate);
System.out.println("Overloaded constructor is called. ");
}
// Part 4 student code ends here.
// 5 ****** write this method:
/** applyInterest method, no parameters, void return value
* call deposit method, passing a month's worth of interest
* remember that interestRate instance variable is annual rate
*/
// Part 5 student code starts here:
public void applyInterest()
{
deposit (super.getBalance() * (interestRate/12.0));
}
// Part 5 student code ends here.
/** accessor method for interestRate
* @return interestRate
*/
public double getInterestRate()
{
return interestRate;
}
/** mutator method for interestRate
* @param newInterestRate new value for interestRate
* newInterestRate must be >= 0.0
* if not, print an error message
*/
public void setInterestRate(double newInterestRate)
{
if (newInterestRate >= 0.0)
{
interestRate = newInterestRate;
}
else
{
System.err.println("Interest rate cannot be negative");
}
}
// 6 ***** write this method
/* toString method
* @return String containing formatted balance and interestRate
* invokes superclass toString to format balance
* formats interestRate as percent using a NumberFormat object
* To create a NumberFormat object for formatting percentages
* use the getPercentInstance method in the NumberFormat class,
* which has this API:
* static NumberFormat getPercentInstance()
*/
// Part 6 student code starts here:
public String toString()
{
NumberFormat percent = NumberFormat.getPercentInstance();
return super.toString()
+ "\n" + "interestRate is " + percent.format(interestRate);
}
// Part 6 student code ends here.
}
До сих пор у меня были проблемы с частью 5. Для начала это не отдельный код. Это большая часть программы банковского счета. Часть «кассира» - это код, который фактически выполняется.Параметры наследования и прохождение через методы
Моя проблема: я не могу получить «SavingsAccount» для очистки компиляции. Никакой процесс, который я пытаюсь выполнить в части 5, не работает. В нем говорится, что он не может прочитать символ, но я не уверен, как именно это может быть неправильно. Я также скомпилировал файл 'teller', но он не будет компилироваться без каких-либо ошибок. Самое главное, что он не может найти классы и символы, которые я не затронул в первую очередь. Я не уверен, что это связано с тем, что у меня нет SavingsAccount для компиляции чисто или нет.
ОШИБКА КОМПЬЮЛЯ: Деятельность-10-1 \ SavingsAccount.java: 68: ошибка: не найден символ депозит (getBalance() * (interestRate/12.0)); ^ символ: метод getBalance() местоположение: класс SavingsAccount 1 ошибка
Tool завершается с кодом выхода 1
Aw, давай! Дайте мне немного больше, чем это. Это совсем не в моей программе. Это просто что-то из stackoverflow. Он остался после того, как я вставил код. – CoderChic
Что делают депозиты() и getBalance()? – MidasLefko
Ваши проблемы начинаются до шага 5. Вы не определили какой-либо конструктор для своего класса. Вы определили два метода с именем BankAccount и вместо этого возвращаете void. Прочтите https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html. Кроме того, если вы спросите об ошибке компиляции, то самое меньшее, что вы должны сделать, это вставить точное и полное сообщение об ошибке. –