I have a small acount in which to deposit, withdrawl, view balance, and exit. Everything runs perfectly however I would like the balance to ajust according to what method I do (withdrawal, deposit, etc.) I started with joptionpane but had the same problem and thought I should just start over. Anyone point me in the right direction?
Main file:
import java.util.Scanner;
public class Bank1
{
public static void main(String[] args)
{
HomeBank obj1 = new HomeBank();
Scanner keyboard = new Scanner(System.in);
String option;
char object;
System.out.println("This is your home banking account" + "\n");
do
{
System.out.println("What would you like to do today?"+ "\n" +
"\nSelect the following: " +
"\n'B' To View Balance." +
"\n'D' To Deposit" +
"\n'W' To Withdrawal" +
"\n'E' To Exit");
System.out.print("Your selection: ");
option = keyboard.next().toUpperCase();
object = option.charAt(0);
System.out.print("\n");
System.out.println("you entered: " +object+ "\n");
if(object =='D')
obj1.deposit();
else if(object =='W')
obj1.withdrawal();
else if(object =='B')
obj1.balance();
else
System.out.println("**Invalid input**" +
"\n Please try again");
} while(object !='E');
System.out.println("The End");
}
}
Class:
import java.util.InputMismatchException;
import java.util.Scanner;
public class HomeBank
{
private double withdrawal, deposit, balance;
public HomeBank()
{
balance = 100;
withdrawal = 50;
deposit = 150;
}
public HomeBank(double bal, double with, double de)
{
balance = bal;
withdrawal = with;
deposit = de;
}
public static void balance()
{
double balance = 250.00d;
System.out.println("You have $" + balance+"dollars");
}
public static void deposit()
{
Scanner keyboard = new Scanner(System.in);
double deposit = 0.00d;
double balance = 250.00d;
boolean goodput =true;
do
{
try
{
System.out.print("How much would you like to deposit today? :");
deposit = keyboard.nextDouble();
if(deposit > 0.00)
{
System.out.println("you entered $" +deposit+" dollars");
System.out.println("you now have $" + (deposit + balance)+" dollars");
goodput = false;
}
else
{
System.out.println("\n**Error**\nYou cannot deposit a "
+ "negative amount\n");
System.out.println("Please try again\n");
goodput = true;
}
}
catch (InputMismatchException x)
{
System.out.println("I'm sorry but that is an invalid input" +
"\nYou will be redirected to the main menu shortly..."+
"\n");
goodput = false;
}
} while (goodput == true);
}
public static void withdrawal()
{
Scanner keyboard = new Scanner(System.in);
double withdrawal = 0.00d;
double balance = 250.00d;
boolean goodput = true;
do
{
try
{
System.out.println("How much would you like to withdrawal?");
withdrawal = keyboard.nextDouble();
if (withdrawal < 0 || withdrawal > balance)
{
System.out.println("You have either entered a negative number"
+ "or trying to withdrawal more than is in your account");
System.out.println("You cannot withdrawal more than $"+balance);
System.out.println("Please try again");
goodput = true;
}
else
{
System.out.println("You now have $" +(balance-withdrawal)+ "dollars");
System.out.println("Thank you for choosing HomeBank\n"
+ "\nYou will be redirected to the main menu\n");
goodput =false;
}
}
catch (InputMismatchException x)
{
System.out.println("I'm sorry but that is an invalid input" +
"\nYou will be redirected to the main menu shortly..."+
"\n");
goodput = false;
}
} while (goodput == true);
}
}
The issue is how you are updating the values. In your methods, you have something that goes like the following:
double deposit = 0.00d;
double balance = 250.00d;
In there, notice how you are putting the double keyword before the variable. By doing that, you are telling Java to create a new variable named deposit and balance in the local scope.
If you want to modify the fields named deposit and balance, you would definitely have to remove the double keyword before them, and optionally put this. in front of the variable. It would look something like the following:
deposit = 0.00d;
balance = 250.00d;
Or
this.deposit = 0.00d;
this.balance = 250.00d;
You would replace all instances of the variables withdraw, balance, and deposit like that, but only the declaration.
The reason you don't need to specify the type is because you already define it in the field declaration. Therefore when you again define it in the method, you are saying to create a new variable with that name and type in the current scope.
Edit:
As Suyash Limaye said, you will have to remove the static keywords from the methods. Having the static keywords prevents the methods from being able to access the non-static fields, which will cause conflicts.
Related
I want it to start again at the most outer for loop, so that if a user messes up the input, they can sign in again and everything work just like if the program started all over again. I tried using continue statements and break statements and using the nicknames for the loops. Like
outer: do {
//loop code
}
then break outer;
The problem is when I do that, it messes up my controlling of the loop. The end statement that asks the user if they want to go back to the main menu. Right now I just have the app exit, if an exception is encountered, using return statement, but If I'm just gonna exit, I might as well just let the app crash. I want to actually resolve the situation and ask the user for valid input.
package main;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.Scanner;
import model.BankAccount;
public class app {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
HashMap<String, BankAccount> accounts = new HashMap<>();
BankAccount sallyAccount = new BankAccount(1000);
BankAccount bobAccount = new BankAccount(2000);
BankAccount naomiAccount = new BankAccount();
accounts.put("Sally", sallyAccount);
accounts.put("Bob", bobAccount);
accounts.put("Naomi", naomiAccount);
String name;
BankAccount account;
int userInput;
double amount;
boolean again;
do
{
again = true;
System.out.println("Login: Enter your name.");
name = console.next();
account = accounts.get(name);
if(account == null)
{
System.out.println("Please enter a valid name.");
return;
}
do
{
System.out.println("1 - Deposit");
System.out.println("2 - Withdraw");
System.out.println("3 - View Balance");
System.out.println("4 - Logout");
userInput = console.nextInt();
switch(userInput)
{
case 1:
System.out.println("Enter amount to deposit: ");
try
{
amount = console.nextDouble();
}
catch(InputMismatchException e)
{
System.out.println("Please enter a numeric amount.");
return;
}
if(amount < 0)
{
System.out.println("You can't withdraw a negative amount");
return;
}
account.deposit(amount);
break;
case 2:
System.out.println("Enter amount to withdraw: ");
try
{
amount = console.nextDouble();
}
catch(InputMismatchException e)
{
System.out.println("Please enter a numeric amount.");
return;
}
if(amount < 0)
{
System.out.println("You can't withdraw a negative amount");
return;
}
account.withdraw(amount);
break;
case 3:
System.out.println(account.getBalance());
break;
case 4:
again = false;
break;
default:
System.out.println("Enter a valid option.");
}
}
while(again);
System.out.println("Back to main menu? 1 - Yes, 2 - No");
try
{
userInput = console.nextInt();
}
catch(InputMismatchException e)
{
System.out.println("Please enter a number");
return;
}
}
while(userInput == 1);
}
}
package model;
public class BankAccount {
private double balance = 0;
public BankAccount() {}
public BankAccount(double balance)
{
this.balance = balance;
}
public void deposit(double amount)
{
balance = balance + amount;
}
public void withdraw(double amount)
{
if((balance - amount) < 0)
{
System.out.println("Transaction Failed: You can't withdraw more than you have.");
}
else
{
balance = balance - amount;
}
}
public double getBalance()
{
return balance;
}
}
You'll be best served by breaking up your main function in multiple functions that handle different parts of the control logic. A good rule of thumb (for beginning programmers) is a function over ~10-15 lines should probably be multiple functions, though it's not an ironclad rule.
I rewrote your program to be multiple functions, but since this seems like a homework problem I won't post the whole thing. Rather, a general strategy with some snippets.
For example, when the user enters an amount to deposit or withdraw. What your programs wants in that moment is a single double, so you could request a single double, and let another method figure out how to get it:
switch (getMenuChoice()) {
case 1:
account.deposit(getDepositOrWithdrawAmount("deposit"));
break;
case 2:
account.withdraw(getDepositOrWithdrawAmount("withdraw"));
break;
// etc.
}
Then, that function is responsible for looping infinitely until the user provides a valid value:
static double getDepositOrWithdrawAmount(String depositOrWithdraw) {
// loop infinitely until we get a valid value
while (true) {
System.out.println("Enter amount to " + depositOrWithdraw);
try {
double amount = console.nextDouble();
if (amount < 0) {
System.out.println("You can't " + depositOrWithdraw + " a negative amount.");
} else {
// valid value! return for deposit / withdraw to use
// , ending the infinite loop
return amount;
}
} catch (InputMismatchException e) {
System.out.println("Please enter a numeric amount.");
// clear the bad token from the stream
// if you don't do this, each time you
// call `nextDouble`, the same value will
// be returned, causing an infinite loop
console.next();
}
}
}
The nice thing about this function is it works in isolation:
public static void main(String[] args) {
System.out.println("Test: " + getDepositOrWithdrawal("test!"));
}
Gives this result:
Enter amount to test!
abc
Please enter a numeric amount.
Enter amount to test!
not-a-number
Please enter a numeric amount.
Enter amount to test!
-5
You can't test! a negative amount.
Enter amount to test!
1000
Test: 1000.0
This lets you test that pieces of your program are working on their own, instead of trying to debug one big program.
You can write other parts of your program as functions as well, but I'll leave that to you.
I have to write a ATM program for my computer science class. It works for the most part, apart from a couple logic problems within the programs itself. So far, from what I can tell, my ATM will deposit the correct amount of money that I tell it to however, when I withdraw money, it does not always withdraw the correct amount if I purposefully make an error (such as trying to take out an amount that is not a multiple of 20). I am also running into an issue where if I try to take out more money then is actually in the account, it will become a negative value, which I do not want to be allowed. I want it not to subtract the value that causes it to become negative and for it to prompt the user until a value less then or equivalent to the balance is able to be taken out. I am rather new to coding so please excuse my rather messy code. My error is probably around the else if statement where option == 3. Here is my code:
import java.io.*;
import java.util.*;
public class aTMLauncher
{
public static int options=0;
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
aTMTester atm = new aTMTester();
System.out.println("Login: \n(case sensitive)");
System.out.print("Username > ");
String usernameInput=input.nextLine();
int count=4;
while (!usernameInput.equals(aTMTester.getUsername()))
{
System.out.println("\nIncorrect input. Please try again. You have " + (count-1) + " trys remaining attempts.");
System.out.println("Login: \n(case sensitive)");
System.out.print("Username > ");
count--;
if(count==0)
{
System.out.println("No remain attempts, system will now exit");
System.exit(0);
}
usernameInput = input.nextLine();
}
System.out.print("Pin > ");
int PINInput=input.nextInt();
int count1=4;
while (PINInput<aTMTester.getPIN() || PINInput>aTMTester.getPIN())
{
System.out.println("\nIncorrect input. Please try again. You have " + (count1-1) + " trys remaining");
System.out.print("Pin > ");
count1--;
PINInput=input.nextInt();
if(count1==0)
{
System.out.println("No remain attempts, system will now exit");
System.exit(0);
}
}
System.out.println("\nWelcome, " + aTMTester.getUsername() +"!");
while(PINInput==2468)
{
atm.main();
options = input.nextInt();
if (options==4)
{
atm.logout();
}
else if(options==2)
{
System.out.println("How much money would you like to deposit?");
System.out.print("$ ");
atm.deposit = input.nextInt();
atm.balance+=atm.deposit;
System.out.println("Your new balance is $" + atm.balance +"0");
}
else if(options==3)
{
System.out.println("How much money will you be withdrawing? \n(Only amounts divisible by 20 are accepted) \n$");
atm.withdraw= input.nextInt();
atm.balance-=atm.withdraw;
if(atm.withdraw%20==0.0)
{
System.out.println("You took out " +atm.withdraw);
System.out.println("Your new balance is $" + atm.balance);
}
while(atm.withdraw%20>0)
{
System.out.println("Invalid withdraw amount. Please retry.");
System.out.println("\nHow much money will you be withdrawing? \n(Only amounts divisible by 20 are accepted)");
atm.withdraw= input.nextInt();
System.out.println("You took out " +atm.withdraw);
System.out.println("Your new balance is $" + atm.balance);
}
if(!(atm.balance>0.0))
{
System.out.println("You are not allowed to take out more then you have in your account \n Please retry");
atm.withdraw= input.nextInt();
}
}
else if(options==1)
{
System.out.println("Your account balance is $"+atm.balance+"0");
}
}
}
}
public class aTMTester
{
private static final String username = "David";
private static final int PIN = 2468;
public static int deposit, withdraw;
public static double balance=0.00;
private String menu;
/*
* Default constructor
*/
public aTMTester()
{
}
public static String getUsername()
{
return username;
}
public static int getPIN()
{
return PIN;
}
public static void main()
{
System.out.println("\n+++++++++++Account: "+ username +"+++++++++++");
System.out.println("1. Check Account Balance");
System.out.println("2. Deposit Checks");
System.out.println("3. Withdraw Money");
System.out.println("4. Logout");
System.out.print("\nWhat would you like to do next?\n");
}
public static void logout()
{
System.out.println("Thanks for usinging the David Vachlon Inc. ATM. We hope you expierence was fast and simple! Have a great day.");
System.exit(0);
}
public static double getBalance()
{
return balance;
}
public static void deposit()
{
balance+=deposit;
}
public static void withdraw()
{
balance-=withdraw;
}
}
You should do atm.balance -= atm.withdraw; after all checks was successfully passed. For instance, you may restructure your code as follows:
boolean ok = false;
while (!ok) {
System.out.println("\nHow much money will you be withdrawing? \n(Only amounts divisible by 20 are accepted)");
atm.withdraw = input.nextInt();
if (atm.withdraw % 20 != 0) {
System.out.println("Invalid withdraw amount. Please retry.");
} else if (atm.balance < atm.withdraw) {
System.out.println("You are not allowed to take out more then you have in your account \n Please retry");
} else if (atm.withdraw < 0) {
// Probably you should not allow to withdraw a negative amount of money
} else {
ok = true;
}
}
atm.balance -= atm.withdraw;
System.out.println("You took out " + atm.withdraw);
System.out.println("Your new balance is $" + atm.balance);
package developer;
import java.util.*;
import java.lang.Math.*;
public class Developer
{
static Scanner console = new Scanner(System.in);
String workType; // This will be either an app, or game
String name;
int pay;
int weekPay;
int hrsWorked;
double tax;
public Developer()
{
name = "Ciaran";
}
Developer(String appType, String coderName)
{
workType = appType;
name = coderName;
}// End developer
Developer(String appType, int pay) // Class to choose the pay rate depending on if it is a game or app
{
System.out.println("Are you coding an app or a game? ");
appType = console.next();
if(appType == "app")
{
pay = 20;
}
if(appType == "game")
{
pay = 30;
}
else
{
System.out.println("Please enter either 'app' or 'game' ");
}
}// End developer
Developer(int hrsWorked, double tax, int weekPay, int pay) // Class to choose the tax bracket which the developer is in
{
System.out.println("Please enter how many hours you have worked this week: ");
hrsWorked = console.nextInt();
weekPay = hrsWorked * pay;
if(weekPay >= 865)
{
tax = 0.4;
}
else
{
tax = 0.21;
}
}// End developer
Developer(int weekPay, int tax) // Gets the pay after tax
{
weekPay = weekPay * tax;
}// End developer
public void display()
{
System.out.println("This display method works");
System.out.println("User: " + name);
}
public static void main(String[] args)
{
Developer myDev = new Developer();
myDev.display();
} // End main
}// End public class developer
I am trying to get this program to ask the user what their name is; if they are developing a game or app and the amount of hours worked on it. With all this information I want to calculate how much the dev earns including tax. I cannot seem to get the display() method to ask the user the questions though and I have no idea what to do. I am hoping somebody out there can help me.
System.in will read input from the command line. You should wrap it with a java.util.Scanner and nextLine like this:
Scanner scanner = new Scanner(System.in);
String user_input = scanner.nextLine();
Be sure to check
scanner.hasNextLine()
before continuing or you'll get an error.
There are few things that could be done differently in your code, so let's break it down:
1.No need to make console static type, you can use:
private Scanner console = new Scanner(System.in);
2.weekPay is of type int, but your tax is double, if you don't want weekPay to be cast to integer, change it to:
double weekPay;
3.Later on, you are calculating weekPay after tax, so let's introduce a variable for that:
double weekPayAfterTax;
4.All these Developer() methods are constructors, and I think you are slightly confused here. Of course, you can have many constructors, but for us, let's keep only the no-params constructor:
public Developer() {
name = "Ciaran";
//you could initialise all the other variables here as well,
//I'll leave it as an exercise for you :)
}
5.Let's create a method that will ask all the questions and set respective variables:
void setData() {
//let's get the name
System.out.print("What's your name: ");
name = console.nextLine();
System.out.print("Are you coding an app or a game? ");
//since we want the user to enter 'app' or 'game'
//we need to loop until we got these
//we can do this by creating endless while loop,
//which we will end when we have correct input
while (true) {
workType = console.next();
if (workType.equals("app")) {
pay = 20.0;
//stop the loop
break;
}
else if (workType.equals("game")) {
pay = 30.0;
//stop the loop
break;
}
else {
System.out.print("Please enter either 'app' or 'game': ");
//back to top
}
}
//ok, we're out the loop, let's get number of hours
System.out.print("Please enter how many hours you have worked this week: ");
hrsWorked = console.nextInt();
//calculate weekPay
weekPay = hrsWorked * pay;
if(weekPay >= 865) {
tax = 0.4;
}
else {
tax = 0.21;
}
//calculate pay after tax
weekPayAfterTax = weekPay - weekPay * tax;
}
6.Let's update our display() method to show all the info:
public void display() {
System.out.println("This display method works");
System.out.println("User: " + name);
System.out.println("Work type: " + workType);
System.out.println("Pay: " + pay);
System.out.println("Week pay: " + weekPay);
System.out.println("Week pay after tax: " + weekPayAfterTax);
}
7.In your main method, you can finally create an instance of Developer class and get the data:
public static void main(String[] args) {
Developer myDev = new Developer();
myDev.setData();
myDev.display();
}
The code above can be improved (such as checking if user entered number where it's expected), and your problem can of course be done differently, but here's the start.
Please check out some tutorials to learn the basics, such as this one, or this one. Most of all, experiment and don't let others put you down for not understanding something.
import java.util.Scanner;
public class cat{
public static void main(String args[]){
System.out.print("Enter a command = ");
double balance = 0;
String a;
//scanner input
Scanner in = new Scanner(System.in);
String command = in.nextLine();
while (in.hasNext()){
if (command.equals("penny")){
balance = balance + 0.01;
System.out.println("balance = " + balance);
}
if (command.equals("nickel")){
balance = balance + 0.05;
System.out.println("balance = " + balance);
}
else {
System.out.println("return" + balance + "to customer");
break;
}
balance++;
}
}
}
I'm trying to create an infinite loop that keeps reading new commands for a vending machine , that may halt only under certain condition - when the input is "return", it prints the current balance in the string "return $XX to customer". (otherwise it keeps adding/subtracting cash to the current balance).
First, I cannot seem to get the if and else part integrated together since both the string commands ("return ~ to customer "& "balance =") appears when I write 'penny'.
Second problem is that my intended infinite command loops just becomes a flow of infinite numbers in my terminal and I can't seem to figure out why.
Don'y know if it's what you're searching to do, but this loops unitil you send the break command:
import java.util.Scanner;
public class cat {
public static void main(String args[]) {
System.out.print("Enter a command = ");
double balance = 0;
String a;
// scanner input
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
String command = in.nextLine();
if (command.equals("penny")) {
balance = balance + 0.01;
System.out.println("balance = " + balance);
} else if (command.equals("nickel")) {
balance = balance + 0.05;
System.out.println("balance = " + balance);
} else if (command.equals("break")) {
break;
} else {
System.out.println("return " + balance + " to customer");
}
balance++;
}
}
}
To fix your broken 'if' add yet another else:
else if (command.equals("nickel")){
With java7 you can use switch:
switch(command) {
case "nickel":
....
break;
case "penny":
.....
break;
default:
.....;
}
For my Java class, we need to make a bank account that has the methods of withdrawing, depositing money, and displaying current balance. In the Tester class, I want to make it ask for the name, the balance, then allow you to choose 1, 2, or 3. Then it repeats the option you choose until you say type "n". The problem is that running this code causes it to say after you deposit money "You deposited (amount of money deposited) in the account (name of account). Your new balance is (this)." The part where it says "this" is the exact same of the amount of money deposited. In other words, it doesn't add it, it just makes the new balance the same as the deposit, regardless of how much was in before. Any help? Thanks.
import java.io.*;
import java.util.*;
public class BankAccount
{
public BankAccount(double b, String n)
{
double balance = b;
String name = n;
}
public void deposit(double d)
{
balance += d;
}
public void withdraw(double w)
{
balance -= w;
}
public String nickname()
{
System.out.print("Enter a new name: ");
Scanner kbIn = new Scanner(System.in);
String n = kbIn.nextLine();
return n;
}
double balance;
String name;
}
And the tester class:
import java.io.*;
import java.util.*;
public class Tester
{
public static void main(String args[])
{
Scanner kbInLine = new Scanner(System.in);
Scanner kbIn = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = kbInLine.nextLine();
System.out.print("Please enter balance: $");
double balance = kbIn.nextDouble();
BankAccount myAccount = new BankAccount(balance, name);
String proceed = "y";
while(proceed.equalsIgnoreCase("y"))
{
System.out.println("\nPlease pick a number. Would you like to...\n\t 1. Deposit\n\t 2. Withdraw\n\t 3. Print Balance\n");
int choice = kbIn.nextInt();
switch(choice)
{
case 1:
System.out.print("How much would you like to deposit?\n\t$");
double deposit = kbIn.nextDouble();
myAccount.deposit(deposit);
System.out.println("You have deposited $" + deposit + " into the account of " + name + ". The new balance is: " + myAccount.balance);
break;
case 2:
System.out.print("How much would you like to withdraw?\n\t$");
double withdraw = kbIn.nextDouble();
if(myAccount.balance - withdraw > 0)
{
myAccount.withdraw(withdraw);
System.out.println("You have withdrawn $" + withdraw + " from the account of " + name + ". The new balance is: " + myAccount.balance);
}
else
{
System.out.println("Sorry, you have insufficient funds for this operation. Your existing balance is $" + myAccount.balance);
}
break;
case 3:
System.out.print("The balance in the account of " + name + " is $" + myAccount.balance);
break;
}
System.out.print("\nWould you like to do another transaction? (Y/N)");
proceed = kbIn.next();
}
System.out.println("\nThank you for banking with us. Have a good day!");
}
}
What's really wierd is that I did a project before this one (it's actually a simplified version) where it deposits and then withdraws a predetermined, coded amount, then outputs the new bank balance, and it does it fine. But the code for BankBalance is the same. Here's the code for those.
BankAccount class is:
public class BankAccount
{
public BankAccount(String nm, double amt) // Constructor
{
name = nm;
balance = amt;
}
public void deposit(double d) // Sets up deposit object as balance += d
{
balance += d;
}
public void withdraw(double w) // Sets up withdraw object as balance -= w
{
balance -= w;
}
public double balance;
public String name;
}
And the Tester class is:
import java.io.*;
import java.util.*;
public class Tester
{
public static void main(String args[])
{
Scanner kbIn = new Scanner(System.in);
System.out.print("Enter your name:");
String name = kbIn.nextLine();
System.out.print("Enter the balance:");
double balance = kbIn.nextDouble();
BankAccount myAccount = new BankAccount(name, balance);
myAccount.deposit(505.22);
System.out.println(myAccount.balance);
myAccount.withdraw(100.00);
System.out.println("The " + myAccount.name + " account balance is, $" + myAccount.balance);
}
}
You're not actually initialising your balance member variable here:
public BankAccount(double b, String n)
{
double balance = b;
This creates a new local variable called balance, to which you assign the value of b. The member variable balance will remain 0 (the default) after this constructor is run.
public BankAccount(double b, String n)
{
double balance = b;
String name = n;
}
--->
public BankAccount(double b, String n)
{
this.balance = b;
this.name = n;
}
Or you can declare balance as static (data class field), and the methods that use this variable as static too.