Method Not Displaying Properly - java

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

Related

Why does it display the value "null" if the conditions of the method are met?

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

(Arraylist) Crashes when user defined String input

The purpose of the program is to let the user input 5 numbers and select which game they would like to compare them to (lotto/lottoplus1/lottoplus2) with each having a unique set of 5 numbers, then to be stored in an arraylist.
The national lottery run three draws on each night: Lotto, Lotto plus one and Lotto plus 2.
generate numbers for each of these draws.
When a user enters a line of numbers they should also enter either:"lotto", "plus1", or "plus2" to specify which of the draws their numbers should be compared to.
This value should then be assigned to that specific line of numbers and the numbers on that line should be compared against each set of Lotto numbers as required.
Heres my problem! When I input my five numbers then lets say 'plus1' to assign the comparison of those numbers to lotteryPlusOne it crashes and outputs this message:
Exception in thread "main" java.lang.NullPointerException at lottoapp.lottoCounter.compareNums(lottoCounter.java:136) at lottoapp.LottoApp.main(LottoApp.java:61) C:\Users\x15587907\AppData\Local\NetBeans\Cache\8.1\executor‌​-snippets\run.xml:53‌​: Java returned: 1 BUILD FAILED (total time: 15 seconds)
Below is line 136 it is in the Instantiable class in the public void compareNums() method
l = madeUpArrayList.get(i); <-----
Main App
package lottoapp;
import javax.swing.JOptionPane;
import java.util.ArrayList;
import java.util.Arrays;
public class LottoApp {
public static void main(String[] args) {
//declare vars/objects/arrays
int[] lottery = new int[5]; //5 Winning numbers
int[] lotteryPlus1 = new int[5]; //5 Winning LP1 numbers
int[] lotteryPlus2 = new int[5]; //5 Winning LP2 numbers
String gameType;
int number1;
int number2;
int number3;
int number4;
int number5;
//array list called madeUpArrayList
ArrayList<lottoCounter> madeUpArrayList = new ArrayList();
//object declare and create
lottoCounter myCount = new lottoCounter();
//winNums/getLottery need to be initialised at top of program
myCount.winNums();
lottery = myCount.getLottery();
lotteryPlus1 = myCount.getLotteryPlus1();
lotteryPlus2 = myCount.getLotteryPlus2();
//Displays winning numbers (Testing Purposes)
System.out.println(Arrays.toString(lottery));
System.out.println(Arrays.toString(lotteryPlus1));
System.out.println(Arrays.toString(lotteryPlus2));
//Array List
for (int i = 0; i < 1; i++) {
lottoCounter l = new lottoCounter();
number1 = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number 1 "));
number2 = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number 2 "));
number3 = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number 3 "));
number4 = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number 4 "));
number5 = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number 5 "));
gameType = JOptionPane.showInputDialog(null, "Select a game type for comparison ... lotto/plus1/plus2");
l.setNumber1(number1);
l.setNumber2(number2);
l.setNumber3(number3);
l.setNumber4(number4);
l.setNumber5(number5);
l.setGameType(gameType);
madeUpArrayList.add(l);
}
//Comparison
myCount.compareNums();
//Output Lotto,Lotto Plus One and Lotto plus Two correct guesses
JOptionPane.showMessageDialog(null, "Guesses correct for Regular Lottery correct is " + myCount.getCorrectLotto());
JOptionPane.showMessageDialog(null, "Guesses correct for Lottery Plus One is " + myCount.getCorrectPlusOne());
JOptionPane.showMessageDialog(null, "Guesses correct for Lottery Plus Two is " + myCount.getCorrectPlusTwo());
}
}
Instantiable Class
package lottoapp;
import java.util.ArrayList;
public class lottoCounter {
//Variables/Constants/data members
private int correctLotto;
private int correctPlusOne;
private int correctPlusTwo;
private int[] lottery = new int[5];
private int[] lotteryPlus1 = new int[5];
private int[] lotteryPlus2 = new int[5];
private int number1;
private int number2;
private int number3;
private int number4;
private int number5;
private String gameType;
private ArrayList<lottoCounter> madeUpArrayList;
//Constructor
lottoCounter() {
correctLotto = 0;
correctPlusOne = 0;
correctPlusTwo = 0;
number1 = 0;
number2 = 0;
number3 = 0;
number4 = 0;
number5 = 0;
gameType = " ";
}
//setters
public void setCorrectLotto(int correctLotto) {
this.correctLotto = correctLotto;
}
public void setCorrectPlusOne(int correctPlusOne) {
this.correctPlusOne = correctPlusOne;
}
public void setCorrectPlusTwo(int correctPlusTwo) {
this.correctPlusTwo = correctPlusTwo;
}
public void setLottery(int[] lottery) {
this.lottery = lottery;
}
public void setLotteryPlus1(int[] lotteryPlus1) {
this.lotteryPlus1 = lotteryPlus1;
}
public void setLotteryPlus2(int[] lotteryPlus2) {
this.lotteryPlus1 = lotteryPlus2;
}
public void setNumber1(int number1) {
this.number1 = number1;
}
public void setNumber2(int number2) {
this.number2 = number2;
}
public void setNumber3(int number3) {
this.number3 = number3;
}
public void setNumber4(int number4) {
this.number4 = number4;
}
public void setNumber5(int number5) {
this.number5 = number5;
}
public void setGameType(String gameType) {
this.gameType = gameType;
}
public lottoCounter(ArrayList<lottoCounter> madeUpArrayList) {
this.madeUpArrayList = madeUpArrayList;
}
//COMPUTE
//Lottery Generator | random num generator (1-40)Lottery
public void winNums() {
for (int i = 0; i < lottery.length; i++) {//Generating 1 to 40 numbers
lottery[i] = (int) Math.floor(1 + Math.random() * 40);//Using Math.random
for (int j = 0; j < i; j++) {
if (lottery[i] == lottery[j]) {
i--;
}
}
}
//Lottery plus 1 generator
for (int i = 0; i < lotteryPlus1.length; i++) {//Generating 1 to 40 numbers
lotteryPlus1[i] = (int) Math.floor(1 + Math.random() * 40);//Using Math.random
for (int j = 0; j < i; j++) {
if (lotteryPlus1[i] == lotteryPlus1[j]) {
i--;
}
}
}
//Lottery plus 2 generator
for (int i = 0; i < lotteryPlus2.length; i++) {//Generating 1 to 40 numbers
lotteryPlus2[i] = (int) Math.floor(1 + Math.random() * 40);//Using Math.random
for (int j = 0; j < i; j++) {
if (lotteryPlus2[i] == lotteryPlus2[j]) {
i--;
}
}
}
}
//Counter for Lottery/LotteryPlusOne/LotteryPlusTwo (COMPARISON)
public void compareNums() {
for (int i = 0; i < 1; i++) {
for (int j = 0; j < 5; j++) {
lottoCounter l;
l = madeUpArrayList.get(i);
if (l.getGameType().equals("lotto")) {
if (lottery[j] == l.getNumber1() || lottery[j] == l.getNumber2() || lottery[j] == l.getNumber3() || lottery[j] == l.getNumber4() || lottery[j] == l.getNumber5()) {
correctLotto++;
}
}
if (l.getGameType().equals("plus1")) {
if (lotteryPlus1[j] == l.getNumber1() || lotteryPlus1[j] == l.getNumber2() || lotteryPlus1[j] == l.getNumber3() || lotteryPlus1[j] == l.getNumber4() || lotteryPlus1[j] == l.getNumber5()) {
correctPlusOne++;
}
}
if (l.getGameType().equals("plus2")) {
if (lotteryPlus2[j] == l.getNumber1() || lotteryPlus2[j] == l.getNumber2() || lotteryPlus2[j] == l.getNumber3() || lotteryPlus2[j] == l.getNumber4() || lotteryPlus2[j] == l.getNumber5()) {
correctPlusTwo++;
}
}
}
}
}
//getters (return values to App Class)
public int getCorrectLotto() {
return correctLotto;
}
public int getCorrectPlusOne() {
return correctPlusOne;
}
public int getCorrectPlusTwo() {
return correctPlusTwo;
}
public int[] getLottery() {
return lottery;
}
public int[] getLotteryPlus1() {
return lotteryPlus1;
}
public int[] getLotteryPlus2() {
return lotteryPlus2;
}
public int getNumber1() {
return number1;
}
public int getNumber2() {
return number2;
}
public int getNumber3() {
return number3;
}
public int getNumber4() {
return number4;
}
public int getNumber5() {
return number5;
}
public String getGameType() {
return gameType;
}
public ArrayList<lottoCounter> getMadeUpArrayList() {
return madeUpArrayList;
}
}
I am not sure about anyone else but it would be nice to have more info, like the data in the arrays: lottery, lotteryPlus1 and madeUpArrayList ect. Just to make sure that they actually have any data in them because according to your Exception you have a java.lang.NullPointerException in your method compareNums in line 136 of your class. Because you did not post line numbers I am not sure when the exception occurs.
I am assuming one of your arrays does not have any data in it or one or more of your arrays do not have 5 total entries of data in it because your for loop iterates 5 times. But again without seeing how or when your arrays are instantiated I do not think it is possible for anyone to confirm that is the cause of your problems. For example lotteryPlus2[] may only have data for lotteryPlus2[0],lotteryPlus2[1],and lotteryPlus2[2] so when j gets to 3 in the loop lotteryPlus2[3] does not exist and throws a java.lang.NullPointerException.
Also I am curious on why you use this for loop for (int i = 0; i < 1; i++){}
This loop only loops once no matter what so why have it there at all since your main method will always run at least once anyways? Honest question, I am a beginner programmer so you may be using it for something that I have no knowledge about.

My return values always equal 0

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

CombSort implementation in java

I am using Comb Sort to sort out a given array of Strings. The code is :-
public static int combSort(String[] input_array) {
int gap = input_array.length;
double shrink = 1.3;
int numbOfComparisons = 0;
boolean swapped=true;
//while(!swapped && gap>1){
System.out.println();
while(!(swapped && gap==1)){
gap = (int)(gap/shrink);
if(gap<1){
gap=1;
}
int i = 0;
swapped = false;
String temp = "";
while((i+gap) < input_array.length){
numbOfComparisons++;
if(Compare(input_array[i], input_array[i+gap]) == 1){
temp = input_array[i];
input_array[i] = input_array[i+gap];
input_array[i+gap] = temp;
swapped = true;
System.out.println("gap: " + gap + " i: " + i);
ArrayUtilities.printArray(input_array);
}
i++;
}
}
ArrayUtilities.printArray(input_array);
return numbOfComparisons;
}
The problem is that while it sorts many arrays , it gets stuck in an infinite loop for some arrays, particularly small arrays. Compare(input_array[i], input_array[i+gap]) is a small method that returns 1 if s1>s2, returns -1 if s1
try this version. The string array is changed to integer array (I guess you can change it back to string version). The constant 1.3 is replaced with 1.247330950103979.
public class CombSort
{
private static final int PROBLEM_SIZE = 5;
static int[] in = new int[PROBLEM_SIZE];
public static void printArr()
{
for(int i=0;i<in.length;i++)
{
System.out.print(in[i] + "\t");
}
System.out.println();
}
public static void combSort()
{
int swap, i, gap=PROBLEM_SIZE;
boolean swapped = false;
printArr();
while ((gap > 1) || swapped)
{
if (gap > 1)
{
gap = (int)( gap / 1.247330950103979);
}
swapped = false;
for (i = 0; gap + i < PROBLEM_SIZE; ++i)
{
if (in[i] - in[i + gap] > 0)
{
swap = in[i];
in[i] = in[i + gap];
in[i + gap] = swap;
swapped = true;
}
}
}
printArr();
}
public static void main(String[] args)
{
for(int i=0;i<in.length;i++)
{
in[i] = (int) (Math.random()*PROBLEM_SIZE);
}
combSort();
}
}
Please find below implementation for comb sort in java.
public static void combSort(int[] elements) {
float shrinkFactor = 1.3f;
int postion = (int) (elements.length/shrinkFactor);
do {
int cursor = postion;
for(int i=0;cursor<elements.length;i++,cursor++) {
if(elements[i]>elements[cursor]) {
int temp = elements[cursor];
elements[cursor] = elements[i];
elements[i] = temp;
}
}
postion = (int) (postion/shrinkFactor);
}while(postion>=1);
}
Please review and let me know your's feedback.

Finding the Min and Max through Inheritance

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.

Categories