How do I keep track of the balance on a bank account? - java

I am going to create a program that keeps track of the balance on a bank account. The program shall use a loop that continues until the user choses to exit by answering no to the question Do you want to continue?.
In the loop the user shall be asked to enter an amount (positive for deposit and negative for withdraw). The amount shall be added/subtracted from an account balance variable. All deposits/withdraws shall be saved as a history so that we can print it later. When the user choses to exit the loop the current account balance together with the account history (from the array/ArrayList) shall be printed.
Now, I want to use an array with ten slots for the history feature.
My question is how can I keep track of the all deposit, withdraw and current account balance (using an array with ten slots for the history feature) so that I can print it out while the user exits the program?
My code:
BankApp class:
package bankapp;
import java.util.Scanner;
public class BankApp {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
askingUser au = new askingUser();
System.out.println("WELCOME TO OUR BANK!\nYou have 100 SEK by default in your account.");
while (true) {
au.userInput();
System.out.println("Do you want to continue? Answer by Yes or No.");
String yesOrNo = input.next();
if (yesOrNo.equalsIgnoreCase("yes")) {
au.userInput();
} else if (yesOrNo.equalsIgnoreCase("no")) {
System.out.println("History: ");
//print out the transaction history
System.exit(0);
} else {
System.out.println("Invalid character input.");
}
}
}
}
askingUser class:
package bankapp;
import java.util.Scanner;
public class askingUser {
Scanner input = new Scanner(System.in);
double initialBal = 100;
public void userInput() {
System.out.println("Enter your amount: (+ve for deposit & -ve for withdraw)");
double inputAmount = input.nextDouble();
if (inputAmount >= 0) {
double newPosAm = initialBal + inputAmount;
System.out.println("Your current balance is: " + newPosAm + " SEK");
} else {
double newNegAm = initialBal + inputAmount;
System.out.println("Your current balace is: " + newNegAm + " SEK");
}
}
}

If you use an array, you have to keep track of the number of elements stored inside and resize the array when necessary. The easiest way would be to keep the history as strings in ArrayList. You would add one message to that list per transaction:
ArrayList<String> history = new ArrayList<String>();
void addToHistory(String transaction) {
history.add(transaction);
}
void printHistory() {
for(String s : history) {
System.out.println(s);
}
}
addToHistory("Withdrawal: 100 SEK" );
addToHistory("Deposit: 200 SEK" );
printHistory();

You need a queue to do that. However, for a simple, fast and primitive implementation you can:
Define an object called Transaction(deposit - double, withdraw - double, current account balance - double)
Add a List of Transactions into askingUser class as an attribute. I strongly recommend renaming the class name to AskingUser to make it seen as object.
At each operation add a new Transaction to end of the List you just added.
At exit, print out the last -say- 10 elements of the List; you can reach it through askingUser object. You can also define a function in askingUser class to print out the last 10 elements, if you make the function work according to selected number of elements, you can add number of Transactions to the function's inputs.

Related

Salary calculation per hour (Java)

I've been trying to write a java program to calculate daily salary relying on hours worked per day. and if it was weekend or no. (boolean value).
The time the user need to write is 0824 it equals to 08:24 (no idea how to ask for hour:minutes pattern and subtract them).
I've been using only one loop to ask for payment Per Hour again and again if the user puts values lower than 28.00$ or higher than 100.00$.
When the program running after asking for paymentPerHour the program stops <terminated> is not shown.
Would appreciate any help. Thanks! :)
(don't pay attention to the class name)
package ouzanFirstProject;
import java.util.Scanner;
public class convertDecToBinary {
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
int paymentPerHour , entryHour = 0 , exitHour = 0;
float totalHour= (exitHour-entryHour)/100;
boolean workedAtWeekend;
float salary = 0;
System.out.println("Please enter the hour you arrived to work (HHMM)");
entryHour=in.nextInt();
System.out.println("Please enter the hour you exit from work(HHMM)");
exitHour=in.nextInt();
System.out.println("Please enter payment per hour (between 28.00 and 100.00):");
paymentPerHour=in.nextInt();
while(paymentPerHour>0) {
if(paymentPerHour<28 ||paymentPerHour>100) {
System.out.println("Please enter payment per hour");
paymentPerHour=in.nextInt();
}
if(paymentPerHour>=28 &&paymentPerHour<=100) {
continue;
}
}
System.out.println("Did you work on weekend ? (True/False)");
workedAtWeekend=in.hasNext();
if(workedAtWeekend){
salary= (float) ((totalHour)*0.20+100);
}
else if (totalHour>=9) {
salary=(float) ((float)(totalHour)*paymentPerHour*1.5);
if(totalHour>11) {
salary = (float)((float)(totalHour)*paymentPerHour*2);
}
}
else if(totalHour<9) {
salary=(float)((float)(totalHour)*paymentPerHour*0.1);
if(totalHour<=1) {
salary= 0;
}
if(totalHour>=15) {
System.out.println("You cant work more than 15 hours a day");
}
if(totalHour<0) {
salary=Math.abs(totalHour)*paymentPerHour;
}
}
System.out.println("You've been working for: "+totalHour+" Hours"+",And your payment is: "+salary);
}
}
You should not use continue; in the loop. It will force the loop to go to the next iteration even if the conditions are met. Instead you should use break; which will terminate the loop if the conditions are met. Also you should not add the condition paymentPerHour>0 because it will skip the loop if the user enters a negative number (thx to Idle_Mind for this one). See the code sample:
while(true)
{
if(paymentPerHour>=28 &&paymentPerHour<=100) {
break; // This will terminate the loop if the conditions are met
}
// This part will only run if the conditions are not met
System.out.println("Please enter payment per hour");
paymentPerHour=in.nextInt();
}

Created a two condition While loop, one condition works as should the other causes an infinite loop

so im still new to java programming and for this program i need to make a program that calculates change for a vending machine. It is based of a 5 cent increment between a value of 25 cents to a dollar. for this assignment if i use a loop to force the user to input a value in bounds i get extra credit, since i originally was going to scratch because i wasnt getting it but soon did im back to using it. only thing is for one of my conditions it creates an infinite loop of the output message and im not sure why. any advice would be appreciated
/** Carmine A
The purpose of this program is to calculate the change to be dispensed from
a vending machine */
//import scanner so user can input data
import java.util.Scanner;
public class lab2Test{
//declaration of variables to be used in program
float changeGiven;
public static void main(String args[]) {
//ties user input variable to class so scanner can use it
int userInput;
int itemCost;
//initiates the keyboard to be used
Scanner keyboard = new Scanner(System.in);
//print statement to tell user how to enter price
System.out.println("Enter price of item from 25 cents to a dollar in 5-cent increments \n"
+ "Do not enter a decimal point");
//user inputs value to be set to variable
userInput= keyboard.nextInt();
//System.out.println("You entered ." +userInput + " as the price");
//while loop to make sure input stays in bounds
while(userInput<25 || userInput>100){
System.out.println("Invalid amount entered! \n"
+ "Please enter an amount between 25 cents and 1 dollar");
while(userInput>25 && userInput<100){
System.out.println("Price is in bounds");
System.out.println("Please enter a valid amount between 25-100");
itemCost=keyboard.nextInt();
}
}
itemCost=userInput;
//print out item cost based off users input
System.out.println("You enetered: " + itemCost +" as the items cost");
}
}
update
ok took what you guys said and made this
//while loop to make sure input stays in bounds
while(userInput<25 || userInput>100){
System.out.println("Invalid amount entered! \n"
+ "Please enter an amount between 25 cents and 1 dollar");
userInput=keyboard.nextInt();
}
thanks for the help! knew it was something dumb, but this is why i ask for help so i can learn
so i believe it is frowned upon if i made another thread for the same program so i will add to this one.
i have completed just about everything i need but am having a few issues.
1. for some reason after i compile and run my code "Change Due:" prints twice, i am unsure why since i only have it once in a print statement but i can be missing it.
2.i need to print out in a money format and for some reason i have tried different formatting options and none will round (i have a feeling it is but it is not displaying because of the second "Change due:" printing) but can be wrong
3. on line 55 i am receiving this message and not sure why C:\Users\finst\Desktop\Intro to Java\Labs\Lab2\lab2Test.java:55: error: incompatible types: possible lossy conversion from double to int
changeRemainder= (changeDue*(double)100);
this is what i currently have:
/** Carmine
The purpose of this program is to calculate the change to be dispensed from
a vending machine */
//import scanner so user can input data
import java.util.Scanner;
public class lab2Test{
//declaration of variables to be used in program
public static void main(String args[]) {
//ties user input variable to class so scanner can use it
double userInput;
double itemCost;
//initiates the keyboard to be used
Scanner keyboard = new Scanner(System.in);
//print statement to tell user how to enter price
System.out.println("Enter price of item from 25 cents to a dollar in
5-cent increments");
//user inputs value to be set to variable
userInput= keyboard.nextDouble();
//while loop to make sure input stays in bounds
while(userInput<(.25) || userInput>(1.00)){
System.out.println("Invalid amount entered! \n"
+ "Please enter an amount between 25 cents and 1
dollar");
userInput=keyboard.nextDouble();
}
//print out item cost based off users input
System.out.println("You entered: " + userInput +" as the items cost");
System.out.println("You entered a dollar to pay with");
//algorithm to calculate change due
int quarters;
int nickels;
int dimes;
int pennies;
int changeRemainder;
double changeDue;
double dollar=1;
//calculates change due
changeDue= (dollar - userInput);
//System.out.printf("%.2f" + "\n" ,changeDue);
//System.out.println("Change due:" + changeDue);
//makes the remainder into a number that can be used
changeRemainder= (changeDue*(double)100);
//calculates the amount of each coin needed to make the change
quarters= (changeRemainder / 25);
changeRemainder= changeRemainder % 25;
dimes= (changeRemainder/10);
changeRemainder= changeRemainder%10;
nickels=(changeRemainder/5);
changeRemainder= changeRemainder%5;
pennies=(changeRemainder);
//output statement to print coin amounts
System.out.println("Quarters: " + quarters);
System.out.println("Dimes: " + dimes);
System.out.println("Nickels: " + nickels);
System.out.println("Pennies: " + pennies);
}
}
As userInput is never updated in the loop then its value does not change and it will potentially loop for ever.
Maybe you mean userInput=keyboard.nextInt(); but you do not need two loops anyway.
userInput=keyboard.nextInt();
while (userInput<25 || userInput>100) {
System.out.println("Invalid amount entered! \n"
+ "Please enter an amount between 25 cents and 1 dollar");
userInput=keyboard.nextInt();
}
You don't need 2 while loops; just one will do. In any case, your while loop checks the 'userInput' variable, but that never changes in the while loop; you are updating the itemCost variable instead.
I would use a Boolean for your while loop, and create an if else statement within this to check for valid entry and calculate the change. Hope this helps!
boolean end = true;
while (end) {
//retrieve user input of cost and assign value to variable
//create an if statement check if the value is valid
if(itemCost >=25 && itemCost <=100){
//retrieve user input for change entered
//calculate change for the user and display it
//end loop
end = false;
} else {
//invalid entry
end = false;
}
}

How to correlate an assigned String value to an Integer value?

I'm writing a code that allows the user to dictate what type of investment they want (Annual, Monthly or Quarterly) and each investment type correlates to a specific integer: i.e. Annual = 1, Monthly = 12, and Quarterly = 4. However when I assigned annual a value, I also need it to correlate to an int value in my investment equation below and am completely stumped on how to do so.
import java.util.Scanner;
import java.lang.Math;
public class CompoundInterest {
public static void main (String [] args)
{
Scanner cool = new Scanner (System.in);
double saving, rate;
int principal, years;
int choice;
System.out.println("Please enter you principal investment:");
/*Print statment prompts user to enter their principal investment*/
principal = cool.nextInt();
System.out.println("Would you like to have a regular investment plan?");
/* Print out statement asks user if they would like to participate in a regular investment plan*/
String question =cool.next();
System.out.println("What type of investment plan would you prefer (Annual, Quarterly, or Monthly)?");
String quest =cool.next();
while (quest.equalsIgnoreCase(("Annual")))
{ String Annual="1";
Annual.equals(choice);
}
System.out.println("Please enter the number of years that you wish to invest for:");
/* Print statement prompts user to enter the number of years that they wish to invest for*/
years = cool.nextInt();
System.out.println("Please enter the return rate per year:");
/* Print statement prompts user to enter the return rate per year*/
rate = cool.nextDouble();
saving = principal*(1+(rate/choice))* Math.pow(choice, years);
System.out.printf("%.2f", saving);
}
Once the type of investment plan is answered, you need to check if the quest variable matches any of the string you are expecting, i.e., Annual, Quarterly, or Monthly.
If the quest matches any of the choices, you assign a correct value to the choice variable, i.e., 1, 4, or 12.
You also may also need to think of situations if the answer doesn't match any of the correct choices.
if ("Annual".equalsIgnoreCase(quest)) {
choice = 1;
} else if ("Quarterly".equalsIgnoreCase(quest)) {
choice = 4;
} else if ("Monthly".equalsIgnoreCase(quest)) {
choice = 12;
} else {
//you need to do something here.
}
I would recommend using an enum that defines the int you want. I'll call the enum Plan and the int term:
public enum Plan {
ANNUAL(1),
QUARTERLY(4),
MONTHLY(12);
int term;
Plan(int term) {
this.term = term;
}
};
You would use this in your code like this (this replaces int choice):
Plan plan = Plan.valueOf(quest.toUpperCase());
saving = principal * (1 + (rate / plan.term)) * Math.pow(plan.term, years);
I think you are going to need different versions of your calculation. The enum approach would support this easily if you added a method to the enum that switches on the value of the enum. You can work out the different implementations of the calculation and define them in the case statements.
double calculateSavings(int principal, double rate, int years) {
switch (this) {
case ANNUAL:
case QUARTERLY:
case MONTHLY:
default:
return principal * (1 + (rate / term)) * Math.pow(term, years);
}
}
If you go this route you would use it in your code like this:
// saving = principal * (1 + (rate / plan.term)) * Math.pow(plan.term, years);
saving = plan.calculateSavings(principal, rate,years);

Why isn't the entered money incrementing onto the previous balance? (in Java)

I am creating a bankteller loop java code. I am trying to ask the user for what amount of money they would like to deposit into their account. I can get this to work once. For example, they will enter in $20 the first time. Then they will decide to put in $10 more. However, instead of displaying the current balance at $30, it only displays the one recently entered (the $10). How do I fix this?
Here is my code for that part of the loop in the menu that calls the class:
else if( userInput == 3 ){
Account account = new Account();
System.out.print("\nHow much would you like to deposit?: ");
float money = input.nextFloat();
account.deposit(money);
}
Here is the code for deposit that is called:
public void deposit(float money) {
if (money < 0) {
System.err.println("Error: Can't deposit negative money.\n");
return;
}
else {
currentBalance = money + currentBalance;
System.out.println("Current balance: $" + currentBalance + "\n");
}
}
You want to maintain the total balance so far. However, the moment you create a new Account object, balance gets initialized to zero and thus losing previous balance.
What you need to do is create an Account object only once and then call deposit on the same Account object.

Calling a method for calculation [duplicate]

This question already has answers here:
How to get the user input in Java?
(29 answers)
Closed 6 years ago.
So I made a class that is supposed to calculate the number of beers needed to become intoxicated. My class receives User Input for the name of the beer, the alcohol content, and then the user's weight to make the calculation.
Here's my whole Beer class
public class Beer {
private String name;
private double alcoholContent;
//Default apple values (Constructors)
public Beer()
{
this.name = "";
this.alcoholContent = 0.0;
}
//Accessors
public String getName()
{
return this.name;
}
public double getAlcoholContent()
{
return this.alcoholContent;
}
//Mutators
public void setName (String aName)
{
this.name = aName;
}
public void setAlcoholContent (double aAlcoholContent)
{
if (aAlcoholContent < 0 || aAlcoholContent > 1)
{
System.out.println("That is an invalid alcohol content");
return;
}
this.alcoholContent = aAlcoholContent;
}
//Methods
public double Intoxicated (double aWeight)
{
double numberOfDrinks = (0.08 + 0.015) * aWeight / (12 * 7.5 * this.alcoholContent);
return numberOfDrinks;
}
This is specifically my intoxicatedmethod in the class (I think it's right):
public double Intoxicated (double aWeight)
{
double numberOfDrinks = (0.08 + 0.015) * aWeight / (12 * 7.5 * this.alcoholContent);
return numberOfDrinks;
}
This is what the output window is supposed to look like, receiving User Input for the weight and then performing the calculation to see how many beers it would take based on the user's input when previously defining two beers to be considered intoxicated:
What’s the weight of the person consuming said beverages?
185
It would take 3.166 "firstBeerName" beers to become intoxicated.
It would take 1.979 "secondBeerName" beers to become intoxicated.
The intoxicated formula was given to me, I don't know how to properly set up my class testing main method file which calls this class to reflect that output.
You need to write a testing class, that contains a main method. In the main method you can create several Beer-Objects.
By iterating over your Beers, you can get the wanted results.
Look here to get information about how to set up a main method.
Create an Array of Beer-Objects in that method with different alcohol content
Get the user input for the weight and then
Iterate over your Array, call intoxicated() and print the results
You are going to want to create a main method which does the following:
1) Prints the prompt for the beer values (name and % alcohol)
2) Takes in user input for those beer values
3) Prints the prompt for the user's weight
4) Takes in the user input for the weight
5) Calculates and prints the result
For printing prompts, you will most likely want to use System.out.println("Some prompt here!");
For taking input, you will most likely want to use a Scanner. You can search around on this website and others, as well as read the documentation, for how to take input with using that class.
Here is an example of a main method:
public static void main(String[] args) {
Beer blueMoon = new Beer("Blue Moon", 5.4);
Beer hoegaarden = new Beer("Hoegaarden", 4.9);
System.out.println("Enter your weight: ");
Scanner input = new Scanner();
Double weight = input.nextLine();
double value = beer1.Intoxicated(weight);
System.out.println("It would take " + value + " of " + blueMoon.getName() + " to become intoxicated.");
}
I would suggest renaming your Intoxicated method to intoxicated, as method names are generally camelCased in Java.
I am not going to give you the exact code because this seems like homework and I already graduated, but that should be enough to get you started. My advice would be to search around for any specific questions you come up with.
You can write a main method like this:
public static void main(String [ ] args)
{
Beer beer1 = new Beer().
beer1.setName("firstBeerName");
beer1.setAlcoholContent(3.166);
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("What’s the weight of the person consuming said beverages?");
double weight = reader.nextDouble();
double answer = beer1.Intoxicated(weight);
System.out.println("It would take "+answer+" "+beer1.getName()+" beers to become intoxicated.")
// similar for beer2
}
I would encourage you to throw IllegalArgumentException when checking condition in setter:
public void setAlcoholContent(double aAlcoholContent) {
if (aAlcoholContent < 0 || aAlcoholContent > 1) {
throw new IllegalArgumentException("Alcohol content can't be more than 1 or less than 0");
}
this.alcoholContent = aAlcoholContent;
}
And for your question you can test it like this:
public static void main(String[] args) {
List<Beer> beers = new ArrayList<>();
beers.add(new Beer("firstBeerName", 0.04));
beers.add(new Beer("secondBeerName", 0.06));
Scanner reader = new Scanner(System.in);
System.out.println("What’s the weight of the person consuming said beverages?");
double weight = reader.nextDouble();
DecimalFormat decimalFormat = new DecimalFormat("0.000");
for(Beer beer : beers){
System.out.println("It would take " + decimalFormat.format(beer.Intoxicated(weight)) + " " + beer.getName() +" beers to become intoxicated.");
}
}
Also you can use loop for creating new beers, just ask user for amount of beers that he can obtain result for, and then create for loop.

Categories