How do I override an abstract method in java? - java

The purpose of this code is to find the amount of items one wishes to buy, the price of those items, and what the sale currently is. For a buy three get one free sale, it would look something like
1 items at 5.0; discount is 0
2 items at 5.0; discount is 0
3 items at 5.0; discount is 5.0
4 items at 5.0; discount is 5.0
The class extends an abstract class whose abstract method is computeDiscount()
However, I have no idea how to make this method function, because it won't except it as static, but if the method isn't static then I can't use it in my code!
I have no idea what to do, and I desperately need help
package homeFolder;
import java.util.Scanner;
public class BuyNItemsGetOneFree extends DiscountPolicy{
static Scanner input = new Scanner(System.in);
static double itemCost;
static int count = count();
static int n = getN();
static double discount = 0;
public static void main(String[] args) {
itemCost = itemCost();
for(int i = 1; i <= count; i ++) {
discount = computeDiscount(i, itemCost);
System.out.println(i + " items at " + itemCost +
"; discount is " + discount);
}
}
public static double itemCost() {
System.out.print("Enter the cost of the item: ");
itemCost = input.nextDouble();
return itemCost;
}
public static int count() {
System.out.print("How many items are you going to buy: ");
count = input.nextInt();
return count;
}
public static int getN() {
System.out.print("How many items must you buy till you got one free? ");
n = input.nextInt();
return n;
}
public double computeDiscount(int count, double itemCost) {
double discount = 0;
if((count % n) == 0)
discount += itemCost;
return discount;
}
}

If you want to do anything with abstraction, you can't be using static methods. Here, it's best to use instance variables combined with a factory method to do all the initilization action.
package homeFolder;
import java.util.Scanner;
public class BuyNItemsGetOneFree extends DiscountPolicy {
// Below are your fields, or instance variables. Notice the lack of static.
final double itemCost;
final int count;
final int n;
public static void main(String[] args) {
// Now you have an instance to work with.
BuyNItemsGetOneFree sale = newInstance();
for(int i = 1; i <= sale.count; i ++) {
double discount = sale.computeDiscount(i, itemCost);
System.out.println(i + " items at " + sale.itemCost +
"; discount is " + discount);
}
}
// Only the factory method can access this.
private BuyNItemsGetOneFree (double itemCost, int count, int n) {
this.itemCost = itemCost;
this.count = count;
this.n = n;
}
public static BuyNItemsGetOneFree newInstance() {
// The scanner really only needs to be used here.
Scanner input = new Scanner(System.in);
// Initilizes itemCost
System.out.print("Enter the cost of the item: ");
double itemCost = input.nextDouble();
// Initilizes count
System.out.print("How many items are you going to buy: ");
int count = input.nextInt();
// Initilizes n
System.out.print("How many items must you buy till you got one free? ");
int n = input.nextInt();
// Constructs and returns
return new BuyNItemsGetOneFree(itemCost, count, n);
}
#Override // Always add this when overriding a method.
public double computeDiscount(int count, double itemCost) {
double discount = 0;
if((count % n) == 0)
discount += itemCost;
return discount;
}
}
If you want to go a step further, there is no need for the parameters in computeDiscount as they are (from what I see) just going to reference fields already able to be used.

Spencer make all your methods static and also your main method is missing static.
it should be something like this public static void main(String [] args)

Related

Trying to figure out how to pass array object data to a separate method

I wanted to write a program that records bar inventory as I'm a bartender. I can't figure out how to pass the liquorCost and liquorCount data to the GetCostTotal() method below the main() method. I'm absolutely sure it's something fairly straightforward that I'm doing incorrectly but I just can't figure it out. Any help is appreciated.
My Liquor class is separate and I can post that if necessary but I don't think it's the class that's giving me the problem, it's retrieving the data input from the array to the separate method.
package inventory;
import java.util.Scanner;
public class Inventory {
public static void main(String[] args) {
System.out.println("How many bottles are you taking inventory of?: ");
Scanner keyboard = new Scanner(System.in);
int size = keyboard.nextInt();
Liquor[] inv = new Liquor[size];
for (int i = 0; i < inv.length; i++) {
inv[i] = new Liquor();
System.out.println("Enter product name: ");
inv[i].setLiquorName(keyboard.next());
System.out.println("Enter the count for the product: ");
inv[i].setLiquorCount(keyboard.nextDouble());
System.out.println("Enter the cost for the product: ");
inv[i].setLiquorCost(keyboard.nextDouble());
}
System.out.println("The sitting inventory cost of these products is: ");
//double totalCost = 0
for (Liquor inv1 : inv) {
System.out.println(inv1.getLiquorName() + ": $" + inv1.getLiquorCost() * inv1.getLiquorCount());
}
double costTotal = GetCostTotal(Liquor[] inv, double liquorCost, double liquorCount);
System.out.println("The total cost of the inventory is: "
+ costTotal);
System.exit(0);
}
public static double GetCostTotal(Liquor[] inv, double liquorCost, double liquorCount) {
double costTotal = 0;
for ( int i = 0; i < inv.length; i++) {
costTotal += (liquorCost * liquorCount);
}
return costTotal;
}
}
try this
public static void main(String[] args) {
System.out.println("How many bottles are you taking inventory of?: ");
Scanner keyboard = new Scanner(System.in);
int size = keyboard.nextInt();
Liquor[] inv = new Liquor[size];
for (int i = 0; i < inv.length; i++) {
inv[i] = new Liquor();
System.out.println("Enter product name: ");
inv[i].setLiquorName(keyboard.next());
System.out.println("Enter the count for the product: ");
inv[i].setLiquorCount(keyboard.nextDouble());
System.out.println("Enter the cost for the product: ");
inv[i].setLiquorCost(keyboard.nextDouble());
}
System.out.println("The sitting inventory cost of these products is: ");
//double totalCost = 0
for (Liquor inv1 : inv) {
System.out.println(inv1.getLiquorName() + ": $" + inv1.getLiquorCost() * inv1.getLiquorCount());
}
double costTotal = GetCostTotal(inv);
System.out.println("The total cost of the inventory is: "
+ costTotal);
System.exit(0);
}
public static double GetCostTotal(Liquor[] inv) {
double costTotal = 0;
for ( int i = 0; i < inv.length; i++) {
costTotal += (inv[i].getLiquorCost() * inv[i].getLiquorCount());
}
return costTotal;
}
Lets understand what went wrong here.Take a look at how you are trying to call the GetCostTotal() method.
double costTotal = GetCostTotal(Liquor[] inv, double liquorCost, double liquorCount);
This is incorrect. The syntax/way you are calling the method is actually used when we what to define a method. Like you did:
public static double GetCostTotal(Liquor[] inv, double liquorCost, double liquorCount) {}
Your call should be like:
double costTotal = GetCostTotal(inv);
Here, we are passing only inv because the data for liquorCost and liquorCount is available inside "each" element of array inv.
Now you can accept this argument in GetCostTotal method. Here as you are iterating using a for loop, you can read the data you needed as inv[i].getLiquorCost() and inv[i].getLiquorCount().
I suggest you can read more on defining a method and calling a method in java.

How to pass variables from one method to another?

Trying to write a grade calculator program and am running into problems passing return variables from one method to another. I'm new to coding so I'm sure this isn't very pretty, but was hoping to get some help.
I have a method to calculate the Homework score, a method to calculate the midterm score, and a method to calculate the final score. I'm trying to call the return variables in the last method to calculate overall grade. The error is when calling the courseScore method, and displays as: The method courseScore(int, int, int) in the type GradeCalc is not applicable for the arguments (). Any help is appreciated!
import java.util.*;
public class GradeCalc {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int overAll;
int midtermScore;
int finalsScore;
hwpoints();
midTerm();
courseScore();
}
public static int hwpoints() {
int x;
int hwTotal = 0;
int pointsPossible = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter number of assignments:");
x = input.nextInt();
for(int i = 1; i <= x; i++) {
System.out.println("Enter assignment score:");
int hwScore = input.nextInt();
hwTotal += hwScore;
System.out.println("Enter total possible points:");
int points = input.nextInt();
pointsPossible += points;
}
int overAll = (hwTotal / x);
System.out.println("You got " + hwTotal + " out of " + pointsPossible + ". Your overall Homework grade is a: " + overAll);
return overAll;
}
public static int midTerm() {
int midtermPoints;
int midtermPossible;
int midtermScore;
Scanner input = new Scanner(System.in);
System.out.println("Enter Midterm Score:");
midtermPoints = input.nextInt();
System.out.println("Enter total possible Midterm Points:");
midtermPossible = input.nextInt();
midtermScore = (midtermPoints / midtermPossible);
System.out.println("Your Midterm score is " + midtermScore);
return midtermScore;
}
public static int finalScore() {
int finalsPoints;
int finalsPossible;
int finalsScore;
Scanner input = new Scanner(System.in);
System.out.println("Enter Finals Score:");
finalsPoints = input.nextInt();
System.out.println("Enter total possible Finals Points:");
finalsPossible = input.nextInt();
finalsScore = (finalsPoints / finalsPossible);
System.out.println("Your Finals score is " + finalsScore);
return finalsScore;
}
public static void courseScore(int finalsScore, int midtermScore, int overAll) {
Scanner input = new Scanner(System.in);
System.out.println("What percent of your grade is the final?");
int testWeight = input.nextInt();
System.out.println("What percent of your grade is the midterm?");
int midtermWeight = input.nextInt();
System.out.println("What percent of your grade is the homework?");
int hwWeight = input.nextInt();
int testWeighted = (finalsScore * (testWeight / 100));
int midtermWeighted = (midtermScore * (midtermWeight / 100));
int hwWeighted = (overAll * (hwWeight / 100));
int courseScore = ((hwWeighted + midtermWeighted + testWeighted) * 100);
System.out.println("Your total course grade is " + courseScore);
}
}
The methods hwpoints, midTerm and finalScore all return an int value which you are not keeping
You need to do some thing like
int hwp = hwpoints ();
int mt = midterm ();
int fs = finalScoare ();
then you can pass these variable into courseScore as
courseScore (fs, mt, hwp);
Note
In this code
int testWeighted = (finalsScore * (testWeight / 100));
you are going to be undertaking integer division.
See Int division: Why is the result of 1/3 == 0?
First thing is to understand the concept of a class and a static method.
Classes have fields and methods.
Fields (variables) hold data (state) that the Methods can operate on
Each instance of a class has its own values for these fields
Methods operate on the Fields
Methods can include call parameters
Methods can also return a value
Static instances (classes, fields, and methods) are singletons
There is only one copy of them (all instances of the class share the same one)
Static Methods cannot access (non-static) fields/methods
Using this, consider creating another class that has (most) of the content of your GradeCalc class and remove the statics from them and create an instance of that class in GradeCalc. That way each method in the class can access the fields you have defined.
Here is an example of the concept based on what you have already written.
Note: You code has other structural/implementation issue and I would never implement it as shown; but, I don't want to turn this into a Java course; so, I tried to show you something that could work within the context of what you had written.
public class GradeCalc {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Calculator calc = new Calculator (calc);
calc.hwpoints();
calc.midTerm();
calc.courseScore();
int overAll = calc.OverAll;
int midtermScore = calc.MidtermScore;;
int overAll = calc.OverAll;
}
public class Calculator {
public void OverAll;
public void MidtermScore;
public void FinalsScore;
public void hwpoints()
{
...
OverAll = overAll
}
//Do the same for the methods below
//public void midTerm();
//public void courseScore();
}

Values don't change when I print them [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 6 years ago.
I am trying to call my methods within main but after entering my dollars and cents, the values don't change when I print them
import java.text.DecimalFormat;
import java.util.Scanner;
public class ChangeMachine {
public static void main(String[] args) {
System.out.println("Change is good");
int dollars = 0;
int cents = 0;
int toonie = dollars/2;
int loonie = dollars%2;
int quarter = cents/25;
int dime = (cents%25)/10;
int nickel = ((cents%25)%10)/5;
ChangeMachine.getAmountFromUser(dollars, cents);
ChangeMachine.calculateCoins(dollars, cents);
ChangeMachine.displayInvoice(dollars, cents, toonie, loonie, quarter, dime, nickel);
}
Method to input the dollars and cents
Here I'm able to enter the amount but it won't appear when I try to display it
public static void getAmountFromUser(int dollars, int cents) {
Scanner input = new Scanner(System.in);
System.out.print("How many dollars? ");
dollars = input.nextInt();
System.out.print("How many cents? ");
cents = input.nextInt();
System.out.println();
input.close();
}
Method to calculate coins
public static void calculateCoins (int dollars, int cents){
DecimalFormat df = new DecimalFormat("#0.00");
double amount = dollars + cents/100.0;
System.out.println("$"+df.format(amount)+" requires:");
//-----Bonus-----
dollars=dollars+(cents+2)/100;
cents=(cents+2)%100;
//---------------
}
Method to display coins needed
public static void displayInvoice (int dollars, int cents, int toonie, int loonie, int quarter, int dime, int nickel){
System.out.println(toonie+" Toonies");
System.out.println(loonie+" Loonies");
System.out.println(quarter+" Quarters");
System.out.println(dime+" Dimes");
System.out.println(nickel+" Nickels");
}
}
... the values don't change when I print them
Yes, they shouldn't be changed because Java is a pass-by-value language. Any primitive variable, that is passed to a method, will not be changed (you are passing just a value of this variable, a new local variable will be created for the method).
How to solve that?
returning a changed value from a method
making operations over instance variables without local variable use
writing a custom class which keeps primitives
EDIT:
When we start talking about returning multiple values from a method, possibly, our methods are built not completely good (e.g. break the single responsibility principle). In that case, we need to refactor our methods. Consider methods with a single responsibility (calculateDollars, calculateCents, displayCoin). It will help to separate your code into small logical parts and make them more independent.
EDIT 2:
Now you are bound up with variables defined in the program's beginning. They, in their turn, are bound up with values of variables at that point. Take a look how you may correct that:
public int getLoonie(int dollars) {
return dollars % 2;
}
Better? Let's call it in the displayInvoice:
System.out.println(getLoonie(dollars) + " Loonies");
or much better
System.out.println(getLoonie(userCash.getDollars()) + " Loonies");
References to parameter arguments (local variables) in Java are pass-by-value, rather than pass-by-reference.
Each method has their own set of local variable references. When you re-assign a new value to a local variable reference, this change is local to that method.
Edit:
Here's one way to do it:
import java.text.DecimalFormat;
import java.util.Scanner;
public final class ChangeMachine {
private ChangeMachine() {
}
public static Cash getAmountFromUser() {
try(final Scanner input = new Scanner(System.in)) {
System.out.print("How many dollars? ");
final int dollars = input.nextInt();
System.out.print("How many cents? ");
final int cents = input.nextInt();
return new Cash(dollars, cents);
}
}
public static void calculateCoins(final Cash cash) {
final DecimalFormat decimalFormat = new DecimalFormat("#0.00");
final double amount = cash.getDollars() + cash.getCents() / 100.0D;
System.out.println("$" + decimalFormat.format(amount) + " requires:");
cash.setDollars(cash.getDollars() + (cash.getCents() + 2) / 100);
cash.setCents((cash.getCents() + 2) % 100);
}
public static void displayInvoice(final Cash cash) {
System.out.println(cash.calculateToonies() + " Toonies");
System.out.println(cash.calculateLoonies() + " Loonies");
System.out.println(cash.calculateQuarters() + " Quarters");
System.out.println(cash.calculateDimes() + " Dimes");
System.out.println(cash.calculateNickels() + " Nickels");
}
public static void main(final String[] args) {
final Cash cash = getAmountFromUser();
calculateCoins(cash);
displayInvoice(cash);
}
private static final class Cash {
private int cents;
private int dollars;
public Cash(final int dollars, final int cents) {
this.dollars = dollars;
this.cents = cents;
}
public int calculateDimes() {
return this.cents % 25 / 10;
}
public int calculateLoonies() {
return this.dollars % 2;
}
public int calculateNickels() {
return this.cents % 25 % 10 / 5;
}
public int calculateQuarters() {
return this.cents / 25;
}
public int calculateToonies() {
return this.dollars / 2;
}
public int getCents() {
return this.cents;
}
public int getDollars() {
return this.dollars;
}
public void setCents(final int cents) {
this.cents = cents;
}
public void setDollars(final int dollars) {
this.dollars = dollars;
}
}
}
Were you able to compile this code before? I was just checking the ChangeMachine, getAmountFromUser, and CalculateCoins methods to check them out in Notepad ++ and came up with several errors. The last two lines of code in getAmountFromUser , System.out.println(); and 'input.close();' don't seem to be necessary.
As for the other errors, I'm seeing a lot of class, interface, or enum expected errors.

Why doesn't my array work?

I'm very new to java (only been using it for 2 days now), and am trying to make a class that lets you input three numbers, and then outputs the average of all three. When the code is like this the output always equals 0 and I don't know why? I am able to get it to work if I change add "static" to all the public integers, but why do I have to do that? Is there another way I can do it without making them static?
import java.util.Scanner;
public class lettuce
{
public int num1;
public int num2;
public int num3;
public static void main(String args[])
{
lettuce lettuceObject = new lettuce();
int total = 0;
int average;
int array[] = {lettuceObject.num1,lettuceObject.num2,lettuceObject.num3};
lettuceObject.getNum1();
System.out.println(lettuceObject.num1);
System.out.println(array[0]);
lettuceObject.getNum2();
System.out.println(lettuceObject.num2);
System.out.println(array[1]);
lettuceObject.getNum3();
System.out.println(lettuceObject.num3);
System.out.println(array[2]);
for(int counter = 0; counter < array.length;counter++)
{
total = total + array[counter];
}
average = total/array.length;
System.out.println("The average of the three numbers is: " + average);
}
public int getNum1()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please type your first number: ");
return num1 = keyboard.nextInt();
}
public int getNum2()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please type your second number: ");
return num2 = keyboard.nextInt();
}
public int getNum3()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please type your third number: ");
return num3 = keyboard.nextInt();
}
}
The output is 0 because you have never initialized your num(s), you're assigning to them on get(s) which you never call - and you're trying to set them in get(s) which isn't the customary approach.
public int num1 = 3;
public int num2 = 3;
public int num3 = 3;
And you should get 3. A getter should look like
public int getNum1()
{
return num1;
}
A setter should look like
public void setNum1(int num1) {
this.num1 = num1;
}
And then you would customarily name your class Lettuce and call it from main like
Lettuce lettuce = new Lettuce();
lettuce.setNum1(10);
System.out.println(lettuce.getNum1());
You would customarily also make your fields private and access them through your mutator and accessor methods (getters and setters)
private int num1;
private int num2;
private int num3;
You could choose to create a constructor
public Lettuce(int num1, int num2, int num3) {
this.num1 = num1;
this.num2 = num2;
this.num3 = num3;
}
You could also calculate the average from "lettuce" with something like
public double average() {
return (num1 + num2 + num3) / 3.0;
}
Edit
Please don't edit your question like that. Also, consider the order of your operations. Your get methods are what set the values. So call them before you create your array!
lettuceObject.getNum1();
lettuceObject.getNum2();
lettuceObject.getNum3();
// Each of those values is 0 until you call the previous three lines.
int array[] = {lettuceObject.num1,lettuceObject.num2,lettuceObject.num3};
System.out.println(array[0]);
System.out.println(array[1]);
System.out.println(array[2]);
As you are new I will give you some more tips they making this work.
1: The static modifier specifies that you don't need to instanciate a Class to use that attribute (variable or method ).
For example, if you have a class with one static variable:
public class Clazz {
static int variable=1;
}
You may call it without creating an instance of Clazz. System.out.println(Clazz.variable); would compile with no problems.
Otherwise, a non-staticattribute will need an Instance of Clazz to be accessed:
Clazz instanceOfClazz = new Clazz();
System.out.println(instanceOfClazz.variable);
2: The type intis native. So, when you create your array, you are passing no values, and after reading the output, your array is not updated.
3: a double variable would be more precise to store the result of an average.
4: last but not least, your getNum method could be merged into just 1 method receiving the message as parameter, so you hace a best and clear reuse of the code. That can be staticbecause it doesn't need to interact with any object of the class Lettuce (with receive as parameter all it needs to execute and return the integer sent by the user, you can assing the return outside the method)
Ps.: by notation, the class name should start with capital letter.
Your final class would look better this way:
import java.util.Scanner;
public class Lettuce
{
public int num1;
public int num2;
public int num3;
public static void main(String args[])
{
Lettuce lettuceObject = new Lettuce();
int total = 0;
double average;
lettuceObject.num1 = lettuceObject.getNum("Please type your first number: ");
System.out.println(lettuceObject.num1);
System.out.println(array[0]);
lettuceObject.num2 = lettuceObject.getNum("Please type your second number: ");
System.out.println(lettuceObject.num2);
System.out.println(array[1]);
lettuceObject.num2 = lettuceObject.getNum("Please type your third number: ");
System.out.println(lettuceObject.num3);
System.out.println(array[2]);
int array[] = {lettuceObject.num1,lettuceObject.num2,lettuceObject.num3};
for(int counter = 0; counter < array.length;counter++)
{
total = total + array[counter];
}
average = total/array.length;
System.out.println("The average of the three numbers is: " + average);
}
public int getNum(String message)
{
Scanner keyboard = new Scanner(System.in);
System.out.println(message);
return keyboard.nextInt();
}
}
Hope this helped.

How to store a double in an array incrementally

this is my first post and I hope someone can help. I have been struggling for ages to understand the problem I have and it looks as though I have done everything right yet problem persists. I have written a simple account program and would like to store the new balance after each transaction into an array index. From printing out balance I can see that it is adding and subtracting properly, however it is updating every single array index with the new balance rather than each incremental index. Can anyone spot my mistake. Thank you for any help with this.
Richard
public class TestAppAccount {
public static void main(String args[]) {
int count = 0;
do {
AppAccount.transaction();
AppAccount.storeBalance();
AppAccount.printBalance();
count++;
//Account1.printBalance2();
} while (count <= 100);
}
public class AppAccount {
public static double[] currentBalance = new double[100];
static Scanner keyboard = new Scanner(System.in);
static double balance;
static int transaction;
public static void transaction() {
System.out.println(" Press 1 to add funds, 2 to withdraw ");
transaction = keyboard.nextInt();
if (transaction == 1) {
System.out.println("Enter an amount to add ");
double amount = keyboard.nextInt();
double newBalance = balance + amount;
balance = newBalance;
} else
{
System.out.println("Enter an amount to withdraw");
double amount = keyboard.nextInt();
double newBalance = balance - amount;
balance = newBalance;
}
}
public static void storeBalance() {
for (int i = 0; i < currentBalance.length; i++) {
currentBalance[i] = balance;
}
}
public static void printBalance() {
System.out.println("Balance: " + balance);
System.out.println("Balance: " + currentBalance[3]);//testing by printing 3rd index
}
}
Your storeBalance() method is iterating through the entire array and updating the values. If you want to only update one value, you'll need to keep track of where you've written up to and only write to the location one after that.
e.g.
Instead of
public static void storeBalance() {
for (int i = 0; i < currentBalance.length; i++) {
currentBalance[i] = balance;
}
}
try this:
static int lastStored = 0;
public static void storeBalance() {
currentBalance[lastStored++] = balance;
}
for (int i = 0; i < currentBalance.length; i++) {
currentBalance[i] = balance;
}
That for loop is setting every value in the array to the value of balance. If each index is supposed to be a different account I would suggest passing an index to each function.
The problem is here:
public static void storeBalance() {
for (int i = 0; i < currentBalance.length; i++) {
currentBalance[i] = balance;
}
}
That for-loop will step through every element in the array, one by one, and will overwrite each value with whatever the current balance is.
There are a couple of ways you could fix this. My first reaction would be to create a variable that tells you the next index to write to:
static int nextIndex = 0;
and then storeBalance() would look like this:
public static void storeBalance() {
currentBalance[nextIndex] = balance;
nextIndex++;
}
You issue is you do a for loop and update every single value. You just want to update once when storeBalance() is called. Keep track of i as a static variable:
static int i = 0;
Then do this:
public static void storeBalance() {
if(i >= currentbalance.length)
i = 0;//restart value so it doesnt do array out of bounds
currentbalance[i] = balance;//update a single value
i++;//increment for next call
}
Make sure you do the out of bounds check. That's what the other answers are forgetting to check. Of course this will over write old values, so you can choose to do something else (what ever seems fitting for your requirements).
Stop pretending that java is c.
Java is not c.
Java likes objects.
Use objects.
Avoid arrays.
Here is some code:
// start Main.java file
public class Main
{
public static void main(String args[])
{
int count = 0;
do
{
AppAccount.transaction();
AppAccount.storeBalance();
AppAccount.printBalance();
count += 1;
}
while (count <= 4);
}
}
// start AppAccount.java file
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class AppAccount
{
private static List<Double> currentBalanceList = new ArrayList<Double>();
private static Scanner keyboard = new Scanner(System.in);
private static double runningBalance;
private static int transaction;
public static void printBalance()
{
System.out.println("Running Balance: " + runningBalance);
}
public static void storeBalance()
{
currentBalanceList.add(runningBalance);
}
public static void transaction()
{
double amount;
System.out.println(" Press 1 to add funds, 2 to withdraw ");
transaction = keyboard.nextInt();
if (transaction == 1)
{
System.out.println("Enter an amount to add ");
amount = keyboard.nextDouble();
runningBalance = runningBalance + amount;
}
else
{
System.out.println("Enter an amount to withdraw");
amount = keyboard.nextDouble();
runningBalance = runningBalance - amount;
}
}
}

Categories