From Java from the Beginning by H.N. King, Chapter 3, page 124, #1... Modify the
ID: 3623413 • Letter: F
Question
From Java from the Beginning by H.N. King, Chapter 3, page 124, #1...Modify the Account class so that the balance variable can never become negative. You'll need to change the primary constructor and the deposit and withdraw methods. If the balance threatens to become negative, set it to zero instead. Hint: Use the Math.max method to determine which is larger, the intended balance or zero.
Now, this is from chapter 3 and "If" statements don't start until chapter 4. I can't wrap my head around *not* using an 'if' statement.
Here is the Account.java:
//////////////////////////////////////////////////////////////
// From JAVA PROGRAMMING: FROM THE BEGINNING, by K. N. King //
// Copyright (c) 2000 W. W. Norton & Company, Inc. //
// All rights reserved. //
// This program may be freely distributed for class use, //
// provided that this copyright notice is retained. //
// //
// Account.java (Chapter 3, page 92) //
//////////////////////////////////////////////////////////////
public class Account {
// Instance variables
private double balance;
// Constructors
public Account(double initialBalance) {
balance = initialBalance;
}
public Account() {
balance = 0.0;
}
// Instance methods
public void deposit(double amount) {
balance += amount;
}
public void withdraw(double amount) {
double overdraft_protection = Math.max(balance, amount);
balance -= overdraft_protection;
}
public double getBalance() {
return balance;
}
Also, here is an example of how to use the Math.max method:
12 // Method generates the greater number among the pair of numbers
13 System.out.println("Method generated results");
14 System.out.println(Math.max(2, 5));
This example of math.max was taken from the following website: http://www.codingdiary.com/developers/developers/diary/javaapi/java/lang/SampleCode/MaxMathExampleCode.html
Explanation / Answer
Dear, Here is the code import java.io.*; import java.util.Scanner;// Needed for the Scanner class class Account { // Instance variables private double balance; // Constructors public Account(double initialBalance) { if(initialBalanceRelated Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.