I am having a issues with this problem. For this problem, I am to write a sub-class that interacts with the superclass.
A company has written a large class BankingAccount with many methods including:
Method/Constructor and Description:
public BankingAccount(Startup s) constructs a BankingAccount object using information in the Startup object s
public void debit(Debit d) records the given debit
public void credit(Credit c) records the given credit
public int getBalance() returns current balance in pennies
I am to design a new class MinMaxAccount whose instances can be used in place of a BankingAccount object but include new behavior of remembering the minimum and maximum balances ever recorded for the account. You should provide the same methods as the superclass, as well as the following new behavior:
Method/Constructor and Description:
public MinMaxAccount(Startup s) constructs a MinMaxAccount object using
information in the Startup object s
public int getMin() returns minimum balance in pennies
public int getMax() returns maximum balance in pennies
The account's constructor sets the initial balance based on the Startup information. Assume that only the debit and credit methods change an account's balance.
I am having issues with recording the min and max values, b/c I am not sure if I am on the right track. Currently, it only returns the latest input. Any suggestions would be appreciated.
// This is the subclass
public class MinMaxAccount extends BankingAccount{
private Startup thing;
private int min;
private int max;
// constructor
public MinMaxAccount(Startup s) {
super(s);
Startup thing = s;
min = Integer.MAX_VALUE;
max = Integer.MIN_VALUE;
}
// returns the lowest balance
public int getMin() {
while (super.getBalance()<min) {
min = super.getBalance();
}
return min;
}
// returns the highest value
public int getMax() {
while (super.getBalance()>max) {
max = super.getBalance();
}
return max;
}
}
The superclass provided by Marty Stepp, there is a lot more than that is needed here:
import java.util.LinkedList;
import java.util.List;
public class BankingAccount {
private int balance;
private List<String> historyTransaction;
private List<String> historyBalance;
public BankingAccount() {
historyTransaction = new LinkedList<String>();
historyBalance = new LinkedList<String>();
}
public BankingAccount(Startup s) {
this.balance = s.startup_getBalance();
historyTransaction = new LinkedList<String>();
historyBalance = new LinkedList<String>();
historyTransaction.add(valueToHistory(s.startup_getBalance()));
historyBalance.add(toString());
}
public void debit(Debit d) {
balance += d.debit_getBalance();
historyTransaction.add(valueToHistory(d.debit_getBalance()));
historyBalance.add(toString());
}
public void credit(Credit c) {
balance += c.credit_getBalance();
historyTransaction.add(valueToHistory(c.credit_getBalance()));
historyBalance.add(toString());
}
public int getBalance() {
return balance;
}
public boolean equals(Object o) {
if(o instanceof BankingAccount) {
return (this.getBalance() == ((BankingAccount) o).getBalance());
}
return false;
}
private String valueToHistory(int value) {
int absValue = Math.abs(value);
return (value < 0 ? "(-" : "") + (absValue / 100) + "." + (absValue % 100 / 10) + (absValue % 100 % 10) + (value < 0 ? ")" : " ");
}
public String toString() {
int absBalance = Math.abs(balance);
return (balance < 0 ? "-" : "") + "$" + (absBalance / 100) + "." + (absBalance % 100 / 10) + (absBalance % 100 % 10);
}
public String historyBalanceToString() {
/*int maxLength = 0;
for(String piece : historyBalance) {
maxLength = Math.max(maxLength, piece.length());
}*/
int maxLength = 8;
String build = "";
for(int i = 0; i < historyBalance.size(); i++) {
for(int j = 0; j < maxLength - historyBalance.get(i).length(); j++) {
build += " ";
}
build += historyBalance.get(i);
if(i != historyBalance.size() - 1) {
build += "\n";
}
}
return build;
}
public String historyTransactionToString() {
String total = toString() + " ";
int maxLength = 0;
for(String piece : historyTransaction) {
maxLength = Math.max(maxLength, piece.length() + 2);
}
maxLength = Math.max(maxLength, total.length() + 2);
String build = "";
for(int i = 0; i < historyTransaction.size() - 1; i++) {
for(int j = 0; j < maxLength - historyTransaction.get(i).length(); j++) {
build += " ";
}
build += historyTransaction.get(i);
build += "\n";
}
build += "+";
for(int i = 0; i < maxLength - (historyTransaction.get(historyTransaction.size() - 1).length() + 1); i++) {
build += " ";
}
build += historyTransaction.get(historyTransaction.size() - 1);
build += "\n";
for(int i = 0; i < maxLength; i++) {
build += "-";
}
build += "\n";
for(int i = 0; i < maxLength - total.length(); i++) {
build += " ";
}
build += total;
return build;
}
public static class Startup {
private int balance;
public Startup(int balance) {
this.balance = balance;
}
public int startup_getBalance() {
return balance;
}
}
public static class Debit {
private int balance;
public Debit(int balance) {
this.balance = balance;
}
public int debit_getBalance() {
return balance;
}
}
public static class Credit {
private int balance;
public Credit(int balance) {
this.balance = balance;
}
public int credit_getBalance() {
return balance;
}
}
// REPLACEME
}
The thing you are missing is that you need to record the min and max when the balance changes, not when it is queried.
Override the methods that change the balance and record the min/max if a new min or max have been set. Return the stored min or max when it is queried.
Related
I'm trying to compile my first major program. Unfortunately in getBestFare() I get "null" coming out all the time. And it shouldn't! I'm asking you guys for help what's wrong.
I rebuilt the entire getBestFare() method but unfortunately it keeps coming up with "null". The earlier code was a bit more messy. Now it's better, but it still doesn't work.
public class TransitCalculator {
public int numberOfDays;
public int transCount;
public TransitCalculator(int numberOfDays, int transCount) {
if(numberOfDays <= 30 && numberOfDays > 0 && transCount > 0){
this.numberOfDays = numberOfDays;
this.transCount = transCount;
} else {
System.out.println("Invalid data.");
}
}
String[] length = {"Pay-per-ride", "7-day", "30-day"};
double[] cost = {2.75, 33.00, 127.00};
public double unlimited7Price(){
int weekCount = numberOfDays/7;
if (numberOfDays%7>0){
weekCount+=1;
}
double weeksCost = weekCount * cost[1];
return weeksCost;
}
public double[] getRidePrices(){
double price1 = cost[0];
double price2 = ((cost[1]*unlimited7Price()) / (unlimited7Price() * 7));
double price3 = cost[2] / numberOfDays;
double[] getRide = {price1, price2, price3};
return getRide;
}
public String getBestFare(){
int num = 0;
for (int i = 0; i < getRidePrices().length; i++) {
if(getRidePrices()[i] < getRidePrices()[num]){
return "You should get the " + length[num] + " Unlimited option at " + getRidePrices()[num]/transCount + " per ride.";
}
}
return null;
}
public static void main(String[] args){
TransitCalculator one = new TransitCalculator(30, 30);
System.out.println(one.unlimited7Price());
System.out.println(one.getRidePrices()[2]);
System.out.println(one.getBestFare());
}
}
Assuming that the array is populated with 20 shipments, calculate the total cost of local shipments in the array.
I tried to create a for loop and then call out the method calcCost() and += it to the variable local so it would save the values I guess
I'm pretty sure the way I wrote the code is wrong so if someone could help me with it that would be great!
package question;
public class TestShipment {
public static void main(String[] args) {
Shipment r1 = new Shipment(
new Parcel("scientific calculator " , 250),
new Address("Dubai","05512345678"),
new Address("Dubai","0505432123"),
"Salim"
);
System.out.println(r1);
Shipment[] arr = new Shipment[100];
arr[5] = r1;
Shipment[] a = new Shipment[20];
double local = 0;
for (int i = 0; i < a.length; i++) {
if (a[i].isLocalShipment()) {
System.out.println(a[i].calcCost());
}
}
}
}
public class Shipment {
public Parcel item;
private Address fromAddress;
private Address toAddress;
public String senderName;
public Shipment(Parcel i, Address f, Address t, String name) {
item = i;
fromAddress = f;
toAddress = t;
senderName = name;
}
//setter
public void setFromAddress(String c, String p) {
c = fromAddress.getCity();
p = fromAddress.getPhone();
}
public boolean isLocalShipment() {
boolean v = false;
if (fromAddress.getCity() == toAddress.getCity()) {
v = true;
} else {
v = false;
}
return v;
}
public double calcCost() {
double cost = 0;
if (fromAddress.getCity() == toAddress.getCity()) {
cost = 5;
} else {
cost = 15;
}
if(item.weight > 0 && item.weight <= 200) {
cost += 5.5;
}
if(item.weight > 200) {
cost += 10.5;
}
return cost = cost * (1 + 0.5); //fix the tax
}
public String toString() {
return "From: " + senderName + "\nTo: " + toAddress
+ "\nParcel: " + item.desc+item.weight + "\ncost: " + calcCost();
}
}
I am having trouble getting my java code to properly output the required results. Not to mention that my System.out.Println isn't prompting for input. All my code is good with no errors. However it just doesn't seem to output anything or request an input.
//Author Adam Duffy
package test1;
import java.util.Scanner;
public class Employee {
public static void main(String [ ] args){}
public String DEF_EMP_NUM = "NO_EMP_NUM";
public double DEF_RATE_PER_HOUR = 20.0;
public double DEF_OVER_TIME_RATE = 40.0;
public double DEF_RATE_HOURS_PER_WEEK = 1.5;
private String empNum;
private double ratePerHour;
private double baseHrsPerWeek;
private double overTimeRate;
// no arg constructor setting width and length to default of 1
public Employee() {
empNum = DEF_EMP_NUM;
ratePerHour = DEF_RATE_PER_HOUR;
baseHrsPerWeek = DEF_RATE_HOURS_PER_WEEK;
overTimeRate = DEF_OVER_TIME_RATE;
}
// all arg constructor
public Employee(String empNum, float ratePerHour, float baseHrsPerWeek, int overTimeRate) {
this.empNum = empNum;
this.ratePerHour = ratePerHour;
this.baseHrsPerWeek = baseHrsPerWeek;
this.overTimeRate = overTimeRate;
}
//setters
public void setempNum(String empNum) {
this.empNum = empNum;
}
public String getempNum() {
return this.empNum;
}
//methods
public double getratePerHour() {
return ratePerHour;
}
public void setratePerHour(float ratePerHour) {
this.ratePerHour = ratePerHour;
}
public double getoverTimeRate() {
return overTimeRate;
}
public int setoverTimeRate(int overTimeRate) {
this.overTimeRate = overTimeRate;
return overTimeRate;
}
public double getbaseHrsPerWeek() {
return baseHrsPerWeek;
}
public void setbaseHrsPerWeek(float baseHrsPerWeek) {
this.baseHrsPerWeek = baseHrsPerWeek;
}
#Override
public String toString() {
return super.toString()
+ "\n["
+ "\nbaseHrsPerWeek = " + baseHrsPerWeek
+ "\noverTimeRate = " + overTimeRate
+ "\nratePerHour = " + ratePerHour
+ "\nempNum = " + empNum
+ "\n]";
}
public double calcWeeksPay(int hours) {
return this.ratePerHour * this.baseHrsPerWeek;
/*#param hours
#return
*/
}
{
Scanner scan = new Scanner(System.in);
int myNum[] = new int[5];
int i;
int sum = 0;
for (i = 0; i < myNum.length; i++) {
System.out.print("Enter the number " + (i + 1) + " : ");
myNum[i] = scan.nextInt();
}
for (i = 0; i < myNum.length; i++) {
System.out.print("The number " + (i + 1) + " : ");
System.out.print(myNum[i] + "\n+");
for (int e = 1; e <= i; e++) {
sum = sum + e;
}
System.out.println(sum);
}
}
}
I just can't seem to get it to work. I'm sure I'm missing something obvious. If I could get some advice, I would be very appreciative.
Updated peice of code , which will accept and print the number on console.
public class Employee {
public static void main(String [ ] args){
Scanner scan = new Scanner(System.in);
int myNum[] = new int[5];
int i;
int sum = 0;
for (i = 0; i < myNum.length; i++) {
System.out.print("Enter the number " + (i + 1) + " : ");
myNum[i] = scan.nextInt();
}
for (i = 0; i < myNum.length; i++) {
System.out.print("The number " + (i + 1) + " : ");
System.out.print(myNum[i] + "\n+");
for (int e = 1; e <= i; e++) {
sum = sum + e;
}
System.out.println(sum);
}
}
public String DEF_EMP_NUM = "NO_EMP_NUM";
public double DEF_RATE_PER_HOUR = 20.0;
public double DEF_OVER_TIME_RATE = 40.0;
public double DEF_RATE_HOURS_PER_WEEK = 1.5;
private String empNum;
private double ratePerHour;
private double baseHrsPerWeek;
private double overTimeRate;
// no arg constructor setting width and length to default of 1
public Employee() {
empNum = DEF_EMP_NUM;
ratePerHour = DEF_RATE_PER_HOUR;
baseHrsPerWeek = DEF_RATE_HOURS_PER_WEEK;
overTimeRate = DEF_OVER_TIME_RATE;
}
// all arg constructor
public Employee(String empNum, float ratePerHour, float baseHrsPerWeek, int overTimeRate) {
this.empNum = empNum;
this.ratePerHour = ratePerHour;
this.baseHrsPerWeek = baseHrsPerWeek;
this.overTimeRate = overTimeRate;
}
//setters
public void setempNum(String empNum) {
this.empNum = empNum;
}
public String getempNum() {
return this.empNum;
}
//methods
public double getratePerHour() {
return ratePerHour;
}
public void setratePerHour(float ratePerHour) {
this.ratePerHour = ratePerHour;
}
public double getoverTimeRate() {
return overTimeRate;
}
public int setoverTimeRate(int overTimeRate) {
this.overTimeRate = overTimeRate;
return overTimeRate;
}
public double getbaseHrsPerWeek() {
return baseHrsPerWeek;
}
public void setbaseHrsPerWeek(float baseHrsPerWeek) {
this.baseHrsPerWeek = baseHrsPerWeek;
}
#Override
public String toString() {
return super.toString()
+ "\n["
+ "\nbaseHrsPerWeek = " + baseHrsPerWeek
+ "\noverTimeRate = " + overTimeRate
+ "\nratePerHour = " + ratePerHour
+ "\nempNum = " + empNum
+ "\n]";
}
public double calcWeeksPay(int hours) {
return this.ratePerHour * this.baseHrsPerWeek;
/*#param hours
#return
*/
}
}
Problem was that you were not having anything in the psvm method and below piece of code
Scanner scan = new Scanner(System.in);
int myNum[] = new int[5];
int i;
int sum = 0;
for (i = 0; i < myNum.length; i++) {
System.out.print("Enter the number " + (i + 1) + " : ");
myNum[i] = scan.nextInt();
}
for (i = 0; i < myNum.length; i++) {
System.out.print("The number " + (i + 1) + " : ");
System.out.print(myNum[i] + "\n+");
for (int e = 1; e <= i; e++) {
sum = sum + e;
}
System.out.println(sum);
}
Which takes the input and print it on console was not having any calling code. it was just a inside the block of code. i just moved it inside the main method and it worked.
I coded multiple methods which use arrays to determine a certain value but they all result in 0 and I don't know why. The goal is to create a list of textbooks in a library and then return the heaviest book, weight, index, average page count and total page count.
public class Project3Driver {
// Data Fields
public static final int SUBJECTS = 5;
public static final int TEXTBOOKS = 10000;
String[] SUBJECT_LIST = {"Biology", "Calculus", "Linear Algebra", "Geology", "C++"};
Textbook[] library = new Textbook[TEXTBOOKS];
Random rand = new Random();
// Constructor that uses min-max system to randomize page count from 500-1500 and randomizes the subject
public Project3Driver() {
for (int i = 0; i < library.length; i++) {
library[i] = new Textbook(SUBJECT_LIST[rand.nextInt(SUBJECTS)], 500 + (int) (Math.random() * ((1500 - 500) + 1)));
}
}
// Methods
// Finds the heaviest book and returns the weight
public double findHeaviest() {
double heaviestBook = library[0].getWeight();
for (int i = 1; i < library.length; i++) {
if (library[i].getWeight() > heaviestBook) {
heaviestBook = library[i].getWeight();
}
}
return heaviestBook;
}
// Finds the heaviest book and returns the index
public int getHeaviest() {
double heaviestBook = library[0].getWeight();
int index = 0;
for (int i = 1; i < library.length; i++) {
if (library[i].getWeight() > heaviestBook)
{
heaviestBook = library[i].getWeight();
index = i;
}
}
return index;
}
// Returns the average page count of the library
public int computeAverageSize() {
int pageCount = 0;
for (int i = 0; i < library.length; i++)
{
pageCount = pageCount + library[i].getPageCount();
}
pageCount = pageCount / library.length;
return pageCount;
}
// Returns the total page count of the library
public int computeTotalPages()
{
int pageCount = 0;
for (int i = 0; i < library.length; i++)
{
pageCount = pageCount + library[i].getPageCount();
}
return pageCount;
}
// Tests each method and prints it (called in the main function)
public void getLibraryStats()
{
System.out.println("Heaviest book is " + library[getHeaviest()].getSubject());
System.out.println("The heaviest book is " + findHeaviest() + " kg");
System.out.println("The heaviest book is at the index " + getHeaviest());
System.out.println("The average book size is " + computeAverageSize());
System.out.println("There are " + computeTotalPages() + " pages total");
}
}
The getPageCount method simply returns the page count and getWeight returns the weight (by multiplying pageCount * 0.0025)
Any help would be greatly appreciated! I feel like it could be a problem with my arrays but I checked multiple times for errors
EDIT:
public class Textbook {
public static final double PAGE_WEIGHT = 0.0025;
public static final int PAGE_KNOWLEDGE = 5;
private String subject;
private int pageCount;
private int unreadPages;
// Start of Constructors
// Default constructor
public Textbook() {
subject = "Object-Oriented Programming";
pageCount = 800;
unreadPages = pageCount;
}
// Constructor with subject only
public Textbook(String textSubject) {
subject = textSubject;
}
// End subject constructor
// Constructor with subject and page count
public Textbook(String bookSubject, int bookPages) {
subject = bookSubject;
unreadPages = pageCount;
} // End subject and page count constructor
// End of Constructors
// Start of Accessor Methods
// Method to return text subject
public String getSubject() {
return subject;
}
// Method to return page count
public int getPageCount() {
return pageCount;
}
// Method to return unread pages
public int getUnreadPageCount() {
return unreadPages;
}
// Method to get weight
public double getWeight() {
return pageCount * PAGE_WEIGHT;
}
// Method to read the pages
public int readPages(int numPages) {
if (numPages > pageCount) {
numPages = pageCount;
}
int knowledgeGained = 0;
if (unreadPages == 0) {
knowledgeGained = numPages * 5 / 2;
} else if (unreadPages <= numPages) {
knowledgeGained = unreadPages * 5 + (numPages - unreadPages) * 5 / 2;
unreadPages = 0;
} else {
knowledgeGained = numPages * 5;
unreadPages -= numPages;
}
return knowledgeGained;
}
}
public class CSC211Project3
{
public static void main(String[] args)
{
Project3Driver librarytester = new Project3Driver();
librarytester.getLibraryStats();
}
}
Your Textbook constructor doesn't initialize pageCount, so it will default to 0.
To fix it, initialize the field:
public Textbook(String bookSubject, int bookPages) {
subject = bookSubject;
pageCount = bookPages;
unreadPages = bookPages;
}
Try using a system out statement in the for loop to debug or debug with breakpoints.
Debugging with system out,
System.out.println("getting formed book weight "+library[i].getWeight())
There might be something wrong in the logic of the Textbook class constructor
The method "aboveAverage" in the following code is not displaying correctly and I've tried everything I can. Could someone please explain what's going wrong?
My code:
import java.util.*;
public class DailyCatch
{
private int fishermanID, fisherID;
private String dateOfSample, date;
private double[] fishCaught = new double[10];
private int currWeight = 0;
private String summary;
private double average;
private int aboveAvg;
public DailyCatch() { }
public DailyCatch (int fishermanID, String dateOfSample)
{
fisherID = fishermanID;
date = dateOfSample;
}
public DailyCatch (int fishermanID, String dateOfSample, String weight)
{
this(fishermanID, dateOfSample);
readWeights(weight);
}
public void addFish(double weight)
{
if (currWeight > 10)
{
// array full
}
else
{
fishCaught[currWeight] = weight;
currWeight += 1; // update current index of array
}
}
private void readWeights(String weightsAsString)
{
String[] weightsRead = weightsAsString.split("\\s+");
for (int i = 0; i < weightsRead.length; i++)
{
this.addFish(Double.parseDouble(weightsRead[i]));
}
}
public String toString()
{
return "Fisherman ID: " + fisherID + "\nDate:" + date + "\nFish Caught with Weights: " + Arrays.toString(fishCaught);
}
public void printWeights()
{
for (int i = 0; i < fishCaught.length; i++)
{
System.out.println(fishCaught[i]);
}
}
public double averageWeight()
{
double sum = 0;
double count = 0;
for (int i = 0; i < fishCaught.length; i++)
{
if (fishCaught[i] != 0)
{
sum += fishCaught[i];
count += 1;
average = sum/count;
}
}
return average;
}
public String getSummary()
{ int storyTellerCount = 0;
int keeperCount = 0;
int throwBackCount = 0;
for (int i = 0; i < fishCaught.length; i++)
{
if (fishCaught[i] > 5)
{
storyTellerCount++;
}
else if (fishCaught[i] >=1 && fishCaught[i] <= 5)
{
keeperCount++;
}
else if (fishCaught[i] < 1 && fishCaught[i] > 0)
{
throwBackCount++;
}
} String summary = ("\nStoryteller - " + storyTellerCount+ "\nKeeper - " + keeperCount + "\nThrowback - " + throwBackCount);
return summary;
}
public int aboveAverage()
{
int greatAvgCount = 0;
for (int i = 0; i < fishCaught.length; i++)
{
if (fishCaught[i] > average)
{
aboveAvg = greatAvgCount++;
}
}
return aboveAvg;
}
}
Test Code:
public class BigBass
{
public static void main (String[]args)
{
//Part 1
DailyCatch monday1 = new DailyCatch(32, "4/1/2013", "4.1 5.5 2.3 0.5 4.8 1.5");
System.out.println(monday1);
//Part 2
DailyCatch monday2 = new DailyCatch(44, "4/1/2013");
System.out.println(monday2);
monday2.addFish(2.1);
monday2.addFish(4.2);
System.out.println(monday2);
//Part 3
System.out.println("\n\nSUMMARY OF FISHERMAN 32");
System.out.println(monday1.getSummary());
//Part 4
double avg = monday1.averageWeight();
System.out.printf("\nThere are %d fish above the average weight of %.1f.", monday1.aboveAverage(), avg);
}
}
I just need to get Part 4 to work here. What it does is return that there have been 2 fish caught that are above average when I know it should be 3. The average is 3.1.
A simple mistake.
public int aboveAverage() {
int greatAvgCount = 0;
for (int i = 0; i < fishCaught.length; i++) {
if (fishCaught[i] > 3.1) {
greatAvgCount++; // no 'return'
}
}
return greatAvgCount;
}
if (fishCaught[i] > 3.1)
{
return greatAvgCount++;
}
First try : 4.1 > 3.1
true
returns 0 ++ which is 0 basically
You can increment the counter inside the loop and keep the return statement for the end only.
try
public int aboveAverage() {
int greatAvgCount = 0;
for (int i = 0; i < fishCaught.length; i++) {
if (fishCaught[i] > 3.1) {
greatAvgCount++;
}
}
return greatAvgCount;
}
This line is your problem,
return greatAvgCount++;
you are incrimenting greatAvgCount then returning its initial value, there should be no "return" on this line
The aboveAverage method should be
public int aboveAverage()
{
int greatAvgCount = 0;
for (int i = 0; i < fishCaught.length; i++)
{
if (fishCaught[i] > 3.1)
{
greatAvgCount++;
}
}
return greatAvgCount;
}
Also, you may just be doing it for debug, in which case fair enough, but hardcoding the "average" as 3.1 is generally considered bad practice. If you want average to be always 3.1 (i.e. its a global average that you've looked up from a book then its more usual to declare a static variable called double AVERAGE=3.1 and then use that where ever average is required, that way if the "book value" changes you only need to change average in one place in your code. If average is calculated from your data obviously you should use the calculated value.
Also not directly related to your problem but why are you using an array for your caught fish with a predefined maximum of 10. If you used an ArrayList you could add to it as you saw fit and it would auto expand to accommodate
private double[] fishCaught = new double[10];
becomes
private ArrayList<Double> fishCaught = new ArrayList<Double>();