Java: malfunctioning else if statement (binarysearch help) - java

So I have spent a whole day working on a little java project and thought I should try asking here before I spend another three hours googling.
So what I am trying to do is use binary search in an if-else statement to access an array that is connected to a class somewhere else in the code.
and so you can see the code:
public class BankProject {
public static void main(String[] args) {
Account[] accountArray = new Account[10];
accountArray[0] = new Account("Dillen Newton", 5555, 9000000.0, 10.0);
accountArray[1] = new Account("Meteor", 5556, 10000.0, 5.5);
accountArray[2] = new Account("Meteorite", 5557, 20000.5, 20.0);
accountArray[3] = new Account("Super Mario", 5558, 100.0, 7.0);
accountArray[4] = new Account("A Person", 5559, 234567.0, 6.0);
accountArray[5] = new Account("Noone", 5560, 97498237.99, 50.0);
accountArray[6] = new Account("Yes", 5561, 5.5, 100.0);
accountArray[7] = new Account("Anonymous", 5562, 222.2, 13.0);
accountArray[8] = new Account("Five Hours", 5563, 7600.0, 40.0);
accountArray[9] = new Account("Who Knows", 5564, 9533.8, 99.0);
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Please Enter A Specified Name");
System.out.println("Dillen Newton");
System.out.println("Meteor");
System.out.println("Meteorite");
System.out.println("Super Mario");
System.out.println("A Person");
System.out.println("Noone");
System.out.println("Yes");
System.out.println("Anonymous");
System.out.println("Five Hours");
System.out.println("Who Knows");
System.out.println("");
String n = reader.next(); // Scans the next token of the input as an int.
if (n.equals("Dillen Newton")){
Arrays.binarySearch(accountArray, "Dillen Newton");
System.out.println("Welcome, Dillen");
} else if (n.equals("Meteor")){
Arrays.binarySearch(accountArray, "Meteor");
System.out.println("Welcome, Meteor!");
} else if (n.equals("Meteorite")){
Arrays.binarySearch(accountArray, "Meteorite");
System.out.println("Hello, Meteorite!");
} else if (n.equals("Super Mario")){
Arrays.binarySearch(accountArray, "Super Mario");
System.out.println("Welcome, Mario");
} else if (n.equals ("A Person")){
Arrays.binarySearch(accountArray, "A Person");
System.out.println("Hi Person!");
} else if (n.equals("Noone")){
Arrays.binarySearch(accountArray, "Noone");
System.out.println("Welcome, Nobody!");
} else if (n.equals("Yes")){
Arrays.binarySearch(accountArray, "Yes");
System.out.println("Yes");
} else if (n.equals("Anonymous")){
Arrays.binarySearch(accountArray, "Anonymous");
System.out.println("Hello There!");
} else if (n.equals("Five Hours")){
Arrays.binarySearch(accountArray, "Five Houres");
System.out.println("Has it been that long already?");
} else if (n.equals("Who Knows")){
Arrays.binarySearch(accountArray, "Who Knows");
System.out.println("I don't");
} else{
System.out.println("Incorrect Account. Please restart and try again");
reader.close();
}
/* Account testAccount = new Account("Dillen Newton", 1122, 20000.0, 4.5);
testAccount.withdraw(2500);
testAccount.deposit(3000);
java.util.Date dateCreated = new java.util.Date();
System.out.println("Date Created:" + dateCreated );
System.out.println("Name:" + testAccount.getName());
System.out.println("Account ID:" + testAccount.getId());
System.out.println("Balance:" + testAccount.getBalance());
System.out.println("Monthly Interest:" + testAccount.getMonthlyInterest());
System.out.println("Process completed.");
}
*/
}
}
class Account {
private String name;
private int id;
private double balance;
private double annualInterestRate;
private Date dateCreated;
public Account(){
name = "";
id = 0;
balance = 0.0;
annualInterestRate = 0.0;
}
public Account(int newId, double newBalance){
id = newId;
balance = newBalance;
}
public Account(String newName, int newId, double newBalance, double newAnnualInterestRate) {
name = newName;
id = newId;
balance = newBalance;
annualInterestRate = newAnnualInterestRate;
}
public String getName(){
return name;
}
public int getId(){
return id;
}
public double getBalance(){
return balance;
}
public double getAnnualInterestRate(){
return annualInterestRate;
}
public void setName(String newName){
name = newName;
}
public void setId(int newId){
id = newId;
}
public void setBalance(double newBalance){
balance = newBalance;
}
public void setAnnualInterestRate(double newAnnualInterestRate){
annualInterestRate = newAnnualInterestRate;
}
public Date getDateCreated(){
return dateCreated;
}
public double getMonthlyInterestRate(){
return annualInterestRate / 12;
}
public double getMonthlyInterest(){
return (balance*getMonthlyInterestRate()/100);
}
public void withdraw(double amount)
{
balance = balance - amount;
}
public void deposit(double amount)
{
balance = balance + amount;
}
}
So I believe that everything so far is correct. But the if-else statement is only considering everything as Incorrect.
What I am trying to do is select an account from the array so that in the next part I can start doing things like withdrawals and deposits and balance checking. Either linear search or binary search it necessary for this project.
I don't know if I need to try something else, or if I am just missing something really simple. Anyway, any help would be appreciated!

comparing String using n.equals("Dillen Newton")

Title of your question is misleading. Your question expressed in last paragraph is about string comparison and has nothing to do with binary search. Indeed with that massive if-else statement you are performing linear search.
I don't know if your task is to implement binary search by yourself or just organize your data. In second case I suggest using TreeMap.
EDIT:
class Account implements Comparable<Account> {
[...]
#Override
public int compareTo(Account another) {
return name.compareTo(another.getName());
}
}
Now in your code you can:
Arrays.sort(accountArray);
int i = Arrays.binarySearch(accountArray, new Account(name, 0, 0, 0));

Related

Using One Object in Multiple Classes

I'm trying to use a setter/getter class in multiple classes to modify a single variable. I understand that I have to use the same object in order for this to work, but I'm unsure on how to make a single object accessible to multiple classes.
public class accountbalance {
private double balance;
//getter
public double getBalance() {
return balance;
}
//Setter
public void setBalance(double newBalance) {
this.balance = newBalance;
}
}
This is where I'm trying to use it first:
public class CreateAccount {
String name;
double social;
int pin;
public CreateAccount()
{
name = "null";
social = 0;
pin = 0;
}
public CreateAccount(String enteredName, double enteredSocial,int enteredPin, double value)
{
name = enteredName;
social = enteredSocial;
pin = enteredPin;
double accountnum = 87495;
accountbalance a1 = new accountbalance();
a1.setBalance(value);
System.out.println(name);
System.out.println(social);
System.out.println("Your new PIN is " + pin);
System.out.println("Your new account balance is " + (a1.getBalance()));
}
}
And then I'm trying to use it again here:
public class deposit {
double enteredAmt;
double amt;
public void deposit() {
System.out.println("Enter an amount to desposit: ");
Scanner in = new Scanner(System.in);
enteredAmt = in.nextDouble();
accountbalance ab1 = new accountbalance();
System.out.println("current balence: " + ab1.getBalance());
amt = ab1.getBalance() + enteredAmt;
ab1.setBalance(amt);
System.out.println("Your new balance is " + (ab1.getBalance()));
}
}
I believe what you're trying to do is use the Command Design Pattern.
If you changed your classes to look more like this, things might work a tad bit better.
public class Account {
// Please do not use SS for an identifier.
private String identifier;
private String name;
// Money needs to be stored in it's lowest common denominator.
// Which in the united states, is pennies.
private long balance;
public Account(String identifier, String name) {
this.identifier = identifier;
this.name = name;
this.balance = 0L;
}
public String getIdentifier() {
return this.identifier;
}
public String getName() {
return this.name;
}
public long getBalance() {
return balance;
}
public void credit(long amount) {
balance =+ amount;
}
public void debit(long amount) {
balance =- amount;
}
}
Then here would be your CreateAccountCommand. It is a bit anemic, but that is ok.
public class CreateAccountCommand {
private String identifier;
private String name;
public CreateAccount(String identifier, String name) {
// Identifier sould actually be generated by something else.
this.identifier = identifier;
name = name;
}
public Account execute() {
return new Account(identifier, name);
}
}
Here is your DepositCommand:
public class DepositCommand {
private Account account;
private long amount;
public DepositCommand(Account account, long amount) {
this.account = account;
this.amount = amount;
}
public void execute() {
this.account.credit(amount);
}
}
WithdrawCommand:
public class WithdrawCommand {
private Account account;
private long amount;
public DepositCommand(Account account, long amount) {
this.account = account;
this.amount = amount;
}
public void execute() {
this.account.debit(amount);
}
}
Then run everything:
public class Run {
public static void main(String... args) {
CreateAccountCommand createAccountCommand = new CreateAccountCommand("12345678", "First_Name Last_Name");
Account account = createAccountCommand.execute();
System.out.println(account.getIdentifier());
System.out.println(account.getName());
System.out.println("Your new account balance in pennies: " + account.getBalance());
// Deposit $100.00
DepositCommand depositCommand = new DepositCommand(account, 10000);
depositCommand.execute();
System.out.println(account.getIdentifier());
System.out.println(account.getName());
System.out.println("Your new account balance in pennies: " + account.getBalance());
// Withdraw $75.00
WithdrawCommand withdrawCommand = new WithdrawCommand(account, 7500);
withdrawCommand.execute();
System.out.println(account.getIdentifier());
System.out.println(account.getName());
System.out.println("Your new account balance in pennies: " + account.getBalance());
}
}

Bank Account class with deposit and withdraw

The brief is to create an Account object with ID of 1122, balance of £20000 annual interest of 4.5%, using withdraw method of £2500 and deposit method of £3000 and the print balance, montlhy interest and the date in which the account was created.
I have written the follwoing code but the in main method the initial balance is wrong supposed to be £20000 and instead is £20500 and the withdraw and deposit is also wrong. The amounts are supposed to be Withdraw = £17,500 and deposit = £20,500. Any suggestions on how to reslove this?
package Account;
import java.util.Date;
class Account {
private int id;
private double balance; //balance for account
private double annualInterestRate; //store interest rate
private Date dateCreated; //store date account created
// no arg constructor for default account
Account() {
id = 0;
balance = 0.0;
annualInterestRate = 0.0;
}
//constructor with specfic id and initial balance
Account (int newId, double newBalance) {
id = newId;
balance = newBalance;
}
//
Account (int newId, double newBalance, double newAnnualInterestRate) {
id = newId;
balance = newBalance;
annualInterestRate = newAnnualInterestRate;
}
//accessor and mutator methods
public int getId() {
return id;
}
public double getBalance() {
return balance;
}
public double getAnnualInterestRate() {
return annualInterestRate;
}
public void setId (int newId) {
id = newId;
}
public void setBalance (double newBalance) {
balance = newBalance;
}
public void setAnnualInterestRate (double newAnnualInterestRate) {
annualInterestRate = newAnnualInterestRate;
}
public void seDateCreated (Date newDateCreated) {
dateCreated = newDateCreated;
}
//Method for monthly interest
double getMonthlyInterestRate() {
return annualInterestRate/12;
}
//Define method withdraw
double withdraw (double amount) {
return balance -= amount;
}
//Define method deposit
double deposit(double amount) {
return balance += amount;
}
public static void main(String[] args) {
java.util.Date dateCreated = new java.util.Date();
Account account1 = new Account (1122, 20000, 0.045); //
//account1.withdraw(2500);
//account1.deposit(3000);
System.out.println("----------------------------------------");
System.out.println(" Welcome to your online account!");
System.out.println("Please find your account details below");
System.out.println("----------------------------------------");
System.out.println("Account ID:" + " " + account1.id);
System.out.println("Initial Balance:" + account1.getBalance());
System.out.println("Balance after Withdraw:" + " " + account1.withdraw(2500));
System.out.println("Balance after deposit" + " " + account1.deposit(3000));
System.out.println("Interest Rate:" + " " + account1.getAnnualInterestRate());
System.out.println("Monthly Interest:" + " " + "£" + account1.getMonthlyInterestRate());
System.out.println("Date Account was Created:" + " " + dateCreated);
System.out.println("------------------------");
System.out.println("The Process is complete");
System.out.println("------------------------");
}
}
You need to comment out/remove the following lines:
public static void main(String[] args) {
java.util.Date dateCreated = new java.util.Date();
Account account1 = new Account (1122, 20000, 0.045); //
//account1.withdraw(2500);
//account1.deposit(3000);
You call withdrawl/deposit twice (you do it again in your print statement later).

Using Accessor methods to access data from another class

I am relatively new to java and learning to program, this being my 8th week at uni. I have been fiddling around with my code for the past day and I have been searching for the past hour or two for a similar question that could help answer my problem but have not found one that helps my particular situation, at least not that I could understand.
For an assignment, I have been asked to write a program with 3 classes(an interface, a store and a product class) and I have been going ok until I need to display data on the interface that is held in the product class. At the moment the code will compile fine but when I run the program and try to use the writeOutput() method I get a stack overflow error. Anyway this is what I have so far:
This is the method I am trying to get to work in the interface class:
private void writeOutput()
{
int productChoice;
Scanner console = new Scanner(System.in);
System.out.println("Please choose a product (1),(2),(3)");
productChoice = console.nextInt();
System.out.println("The records of product " +productChoice+ " are:");
System.out.println("Name: "+matesStore.getName());
And this is one of the methods from the store class:
public String getName()
{
return getName();
}
Finally I'll include the getter and setter from the product class just in case:
public void setName(String newName)
{
name = newName;
}
public String getName()
{
return name;
}
Hopefully this is enough information for someone to be able to help me but if it is not, I am happy to upload all three classes in their entirety.
Cheers Cale.
Edit: I have decided to add all three classes to help people who wish to help me (just keep in mind that I am nowhere near finishing and my code is probably riddled with problems) Hopefully it's not too messy for you guys to understand. And sorry for not writing many comments, it's something i need to work on :)
import java.util.*;
public class MatesInterface
{
Store matesStore = new Store();
private void run()
{
showInterface();
chooseOption();
}
private void showInterface()
{
System.out.println("What would you like to do?:");
System.out.println("(1)Input data for the product");
System.out.println("(2)Show data from one product");
System.out.println("(3)Show the replenishment strategy for a product");
System.out.println("(0)Exit the program");
}
private void chooseOption()
{
int option;
boolean flag = false;
Scanner console = new Scanner(System.in);
System.out.print("Please choose an option: ");
option = console.nextInt();
if(option==1)
{
readInput();
}
else if(option==2)
{
writeOutput();
}
else if (option==3)
{
}
else if(option==0)
{
}
else
{
flag = true;
}
while (flag)
{
System.out.println("That is not a valid option.");
System.out.println("Please choose an option: ");
option = console.nextInt();
flag = false;
}
}
private void readInput()
{
Store matesStore = new Store();
String name;
int productChoice, demandRate;
double setupCost, unitCost, inventoryCost, sellingPrice;
Scanner console = new Scanner(System.in);
System.out.println("Please choose a product (1), (2) or (3): ");
productChoice = console.nextInt();
System.out.println("Please enter the product's name: ");
name = console.next();
System.out.println("Please enter the product's demand rate: ");
demandRate = console.nextInt();
System.out.println("Please enter the product's setup cost: ");
setupCost = console.nextDouble();
System.out.println("Please enter the product's unit cost: ");
unitCost = console.nextDouble();
System.out.println("Please enter the product's inventory cost: ");
inventoryCost = console.nextDouble();
System.out.println("Please enter the product's selling price: ");
sellingPrice = console.nextDouble();
matesStore.addData(productChoice, name, demandRate, setupCost, unitCost, inventoryCost, sellingPrice);
chooseOption();
}
private void writeOutput()
{
int productChoice;
Scanner console = new Scanner(System.in);
System.out.println("Please choose a product (1),(2),(3)");
productChoice = console.nextInt();
System.out.println("The records of product " +productChoice+ " are:");
System.out.println("Name: "+matesStore.getName());
}
public static void main (String[] args)
{
MatesInterface intFace = new MatesInterface();
intFace.run();
}
}
public class Store
{
// instance variables - replace the example below with your own
private Product product1, product2, product3;
public Store()
{
product1 = new Product();
product2 = new Product();
product3 = new Product();
}
public void addData(int option, String newName, int newDemand, double newSetup, double newUnit, double newInventory, double newPrice)
{
if (option==1) setData(product1, newName, newDemand, newSetup, newUnit, newInventory, newPrice);
else if (option==2) setData(product2, newName, newDemand, newSetup, newUnit, newInventory, newPrice);
else setData(product3, newName, newDemand, newSetup, newUnit, newInventory, newPrice);
}
private void setData(Product product, String name, int demandRate, double setupCost, double unitCost, double inventoryCost, double sellingPrice)
{
product.setName(name);
product.setDemand(demandRate);
product.setSetup(setupCost);
product.setUnit(unitCost);
product.setInventory(inventoryCost);
product.setPrice(sellingPrice);
}
public String getName()
{
return getName();
}
}
import static java.lang.Math.*;
public class Product
{
private String name;
private int demandRate;
//private final int REPLENISHMENTRATE=0;
private double setupCost;
private double unitCost;
private double inventoryCost;
private double sellingPrice;
//Constructors for the class Product
public Product()
{
name = "No name yet.";
demandRate = 0;
unitCost = 0;
setupCost = 0;
inventoryCost = 0;
sellingPrice = 0;
}
public Product(String newName, int newDemand, double newSetup, double newUnit, double newInventory, double newPrice)
{
name = newName;
demandRate = newDemand;
unitCost = newUnit;
setupCost = newSetup;
inventoryCost = newInventory;
sellingPrice = newPrice;
}
// Accessor and mutator methods to access and modify data on a Product object
public void setName(String newName)
{
name = newName;
}
public String getName()
{
return name;
}
public void setDemand(int newDemand)
{
demandRate = newDemand;
}
public int getDemand()
{
return demandRate;
}
public void setUnit(double newUnit)
{
unitCost = newUnit;
}
public double getUnit()
{
return unitCost;
}
public void setSetup(double newSetup)
{
setupCost = newSetup;
}
public double getSetup()
{
return setupCost;
}
public void setInventory(double newInventory)
{
inventoryCost = newInventory;
}
public double getInventory()
{
return inventoryCost;
}
public void setPrice(double newPrice)
{
sellingPrice = newPrice;
}
public double getPrice()
{
return sellingPrice;
}
}
The method from the store class is recursivelly calling itself with no terminating clause, this is leading to StackOverflowError :
public String getName()
{
return getName(); // calls itself
}
Instead return the value of name variable if it exists in Store class, or whatever variable you want to be returned as a name:
public String getName()
{
// determine the product name you want
return myProduct.getName();
}

my getAverageBalance method always returns 0

So I have an Account class, and a TestAccount class. In the TestAccount class I need to call my getAverageBalance method to find the average balance of all the accounts I have created. Here is the code for my average balance method:
public static double getAverageBalance()
{
if (numberOfAccounts > 0)
return totalValueOfAccounts / numberOfAccounts;
else
return 0;
}
The problem is, it is always returning false on the if statement and I don't know why. Here is the rest of my account class code
public class Account
{
private int id;
private double balance;
private static double annualInterestRate;
private java.util.Date dateCreated;
private static int numberOfAccounts;
private static double totalValueOfAccounts;
public Account()
{
dateCreated = new java.util.Date();
}
public Account(int newId, double newBalance, double newAnnualInterestRate)
{
this.id = newId;
this.balance = newBalance;
dateCreated = new java.util.Date();
this.annualInterestRate = newAnnualInterestRate;
}
public int getId()
{
return this.id;
}
public double getBalance()
{
return balance;
}
public double getAnnualInterestRate()
{
return annualInterestRate;
}
public static double getNumberOfAccounts()
{
return numberOfAccounts;
}
public static double getTotalValueOfAccounts()
{
return totalValueOfAccounts;
}
public void setId(int newId)
{
this.id = newId;
}
public void setAnnualInterestRate(int newAnnualInterestRate)
{
this.annualInterestRate = newAnnualInterestRate;
}
public void setBalance(double newBalance)
{
this.balance = newBalance;
}
public static void setAnnualInterestRate(double newAnnualInterestRate)
{
annualInterestRate = newAnnualInterestRate;
}
public double getMonthlyInterest()
{
return this.balance * (annualInterestRate / 1200);
}
public java.util.Date getDateCreated()
{
return this.dateCreated;
}
public void withdraw(double amount)
{
this.balance -= amount;
}
public void deposit(double amount)
{
this.balance += amount;
}
public void awardMonthlyInterestRate()
{
this.balance += getMonthlyInterest();
}
public void closeAccount()
{
System.out.println("Closing account " + id);
this.numberOfAccounts -= 1;
this.totalValueOfAccounts -= balance;
}
Here is the testaccount code:
public class TestAccount
{
public static void printAccount(Account acct)
{
System.out.printf("%5d $%9.2f %5.2f%% %29s\n\n", acct.getId(), acct.getBalance(), acct.getAnnualInterestRate(), acct.getDateCreated());
}
public static void main(String[] args)
{
System.out.println("The average account balance is: " + Account.getAverageBalance());
System.out.println();
Account a = new Account();
System.out.println("Default account: ");
printAccount(a);
a.setId(1122);
a.setBalance(20000);
a.setAnnualInterestRate(4.5);
System.out.println("Modified account: ");
printAccount(a);
a.withdraw(2500);
a.deposit(3000);
System.out.println("After withdraw and deposit: ");
printAccount(a);
a.awardMonthlyInterestRate();
a.awardMonthlyInterestRate();
a.awardMonthlyInterestRate();
a.awardMonthlyInterestRate();
a.awardMonthlyInterestRate();
a.awardMonthlyInterestRate();
System.out.println("After 6 months of interest: ");
printAccount(a);
System.out.println("The average account balance is: " + Account.getAverageBalance());
a.closeAccount();
System.out.println();
Account[] accts = new Account[5];
for (int i = 0; i < accts.length; i++)
{
accts[i] = new Account(i+1, (double) Math.floor(Math.random()*100000), 3.0 );
}
System.out.println("Array of five accounts with random balances:");
for (int i = 0; i < accts.length; i++)
{
printAccount(accts[i]);
}
System.out.println("The average account balance is: " + Account.getAverageBalance());
System.out.println();
System.out.println("Array after awarding 6 months of interest: ");
for (int i = 0; i < accts.length; i++)
{
Account b = accts[i];
for (int j = 0; j < 6; j++)
{
b.awardMonthlyInterestRate();
}
printAccount(accts[i]);
}
System.out.println("The average account balance is: " + Account.getAverageBalance());
}
}
I think perhaps you are missing a line inside your constructor:
public Account() {
dateCreated = new java.util.Date();
numberOfAccounts++;
}
If you never increment numberOfAccounts, I am not sure how you expect to ever get a value above 0. This is particularly unfortunate because that variable is private, so only a method of Account even has a chance of setting it.
You need to add the same line to your second constructor, but you can simplify by calling the first constructor. You also need to add to your totalValueOfAccounts.
public Account(int newId, double newBalance, double newAnnualInterestRate)
{
this(); // call the first constructor
this.id = newId;
this.balance = newBalance;
this.annualInterestRate = newAnnualInterestRate;
totalValueOfAccounts += newBalance;
}
You also need to update the variable totalValueOfAccounts inside every method that modifies an individual balance, such as the following:
public void setBalance(double newBalance)
{
totalValueOfAccounts -= this.balance;
totalValueOfAccounts += newBalance;
this.balance = newBalance;
}

java how to compute [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
How can I compute for the balance? I want to subtract withdrawn amount to the saved entered amount of the user.
Here's my code:
AccountInformation.java
public class AccountInformation
{
private int acct_no;
private String name;
private String address;
private String bday;;
public void setAcct_No(int an)
{
this.acct_no = an;
}
public void setName(String n)
{
this.name = n;
}
public void setAddress(String ad)
{
this.address = ad;
}
public void setBday(String bd)
{
this.bday = bd;
}
public int getAcct_No()
{
return this.acct_no;
}
public String getName()
{
return this.name;
}
public String getAddress()
{
return this.address;
}
public String getBday()
{
return this.bday;
}
}
SavingsAccount.java
import javax.swing.*;
public class SavingsAccount extends AccountInformation
{
private int withdraw;
private int balance;
private int amount;
public void setAmount(int am)
{
this.amount = am;
}
public void setWithdraw(int w)
{
this.withdraw = w;
}
public void setBalance(int b)
{
this.balance = b;
}
public int getAmount()
{
return this.amount;
}
public int getWithdraw()
{
return this.withdraw;
}
public int getBalance()
{
return this.balance = amount - withdraw;
}
}
CheckingAccount.java
import javax.swing.*;
public class CheckingAccount extends AccountInformation
{
private int issue_date;
public void setIssue_Date(int id)
{
this.issue_date = id;
}
public int getIssue_Date()
{
return this.issue_date;
}
}
BankAccount.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class BankAccount extends JFrame implements ActionListener
{
private JLabel acct_noL, nameL, addressL, bdayL, amountL;
private JTextField acct_noTF, nameTF, addressTF, bdayTF, amountTF;
private JButton addB, checkB, clearB, exitB;
SavingsAccount[] savings = new SavingsAccount[10];
private int index = 0;
private int acct_no = 1000;
public BankAccount()
{
for(int ctr=0;ctr<=9;ctr++)
{
savings[ctr] = new SavingsAccount();
}
setTitle("Bank Account");
setDefaultCloseOperation(EXIT_ON_CLOSE);
acct_noL = new JLabel("Account Number",SwingConstants.RIGHT);
nameL = new JLabel("Name",SwingConstants.RIGHT);
addressL = new JLabel("Address",SwingConstants.RIGHT);
bdayL = new JLabel("Birthday",SwingConstants.RIGHT);
amountL = new JLabel("Amount to Deposit",SwingConstants.RIGHT);
acct_noTF = new JTextField(10);
nameTF = new JTextField(10);
addressTF = new JTextField(10);
bdayTF = new JTextField(10);
amountTF = new JTextField(10);
acct_noTF.setText("1000");
addB = new JButton("Add");
checkB = new JButton("Check Balance");
clearB = new JButton("Clear");
exitB = new JButton("Exit");
addB.addActionListener(this);
checkB.addActionListener(this);
clearB.addActionListener(this);
exitB.addActionListener(this);
Container pane = getContentPane();
pane.setLayout(new GridLayout(7,2));
pane.add(acct_noL);
pane.add(acct_noTF);
pane.add(nameL);
pane.add(nameTF);
pane.add(addressL);
pane.add(addressTF);
pane.add(bdayL);
pane.add(bdayTF);
pane.add(amountL);
pane.add(amountTF);
pane.add(addB);
pane.add(checkB);
pane.add(clearB);
pane.add(exitB);
}
private String showAccountInfo(int an)
{
String info="";
for(int s=0;s<=9;s++)
{
if(savings[s].getAcct_No()==an)
{
info = "Account Number: " + savings[s].getAcct_No() + "\nName: " + savings[s]. getName() +
"\nAddress: " + savings[s].getAddress() + "\nBirthday " + savings[s].getBday() +
"\nBalance: " + savings[s].getAmount();
}
}
return info;
}
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
int inputAcct_No;
int ewithdraw;
int eissue_date;
if(source==addB)
{
if(index<=9)
{
savings[index].setAcct_No(acct_no);
savings[index].setName(nameTF.getText());
savings[index].setAddress(addressTF.getText());
savings[index].setBday(bdayTF.getText());
savings[index].setAmount(Integer.parseInt(amountTF.getText()));
index++;
acct_no++;
acct_noTF.setText(""+acct_no);
nameTF.setText(null);
addressTF.setText(null);
bdayTF.setText(null);
amountTF.setText(null);
JOptionPane.showMessageDialog(null,"Bank Account Saved!");
}
else
{
JOptionPane.showMessageDialog(null,"Bank Accounts are Full!");
}
}
if(source==checkB)
{
SavingsAccount savings = new SavingsAccount();
CheckingAccount checking = new CheckingAccount();
inputAcct_No = Integer.parseInt(JOptionPane.showInputDialog("Enter Account Number"));
JOptionPane.showMessageDialog(null,this.showAccountInfo(inputAcct_No));
int confirm_withdraw = JOptionPane.showConfirmDialog(null,"Would you like to withdraw?");
if(confirm_withdraw==JOptionPane.YES_OPTION)
{
savings.setWithdraw(Integer.parseInt(JOptionPane.showInputDialog("Enter amount to be withdrawn")));
JOptionPane.showMessageDialog(null,"Your balance is: " + (savings.getBalance()));
int confirm_issue_date = JOptionPane.showConfirmDialog(null,"Would you like to issue cheque?");
if(confirm_issue_date==JOptionPane.YES_OPTION)
{
String Receiver = JOptionPane.showInputDialog(null,"Enter name of the receiver");
checking.setIssue_Date(Integer.parseInt(JOptionPane.showInputDialog("Enter amount to be issued")));
JOptionPane.showMessageDialog(null,"Cheque is issued to " + Receiver + " with the amount of " +checking.getIssue_Date() +
"\nYour balance is: " + (savings.getBalance()-checking.getIssue_Date()));
}
}
else if(confirm_withdraw==JOptionPane.NO_OPTION)
{
}
else if(confirm_withdraw==JOptionPane.CANCEL_OPTION)
{
}
}
if(source==clearB)
{
nameTF.setText(null);
addressTF.setText(null);
bdayTF.setText(null);
amountTF.setText(null);
}
if(source==exitB)
{
System.exit(0);
}
}
public static void main(String[] args)
{
BankAccount ba = new BankAccount();
ba.setSize(500,400);
ba.setVisible(true);
ba.setResizable(false);
ba.setLocationRelativeTo(null);
}
}
"I want to subtract withdrawn amount to the saved entered amount of the user."
Here's is your withdraw code
public void setWithdraw(int w)
{
this.withdraw = w;
}
There is no need to even have a withdraw field to set, unless you want a list of transactions or something, which you don't have. So take out the withdraw field from the class. It doesn't need to be set. And just do something like this
public void withdraw(int amount)
{
balance -= amount;
}
All you need to do is subtract the amount from the balance. Do the same with your deposits (If you decide to add a deposit method. After all, what's an account if you can't deposit).
EDIT
Also you're creating a new Account every time actionPerformed is called
SavingsAccount Savings = new SavingsAccount();
CheckingAccount checking = new CheckingAccount();
Don'r do that. That's why the widthraw amount is always the same as the balance. Instead put them as class member. And remove the above code from the actionPerformed
UPDATE
Try running this very simple program. You will see how withdrawing should work
import java.util.Scanner;
public class AccountTest {
public static void main(String[] args) {
Account account = new Account(1000.00);
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a Amount to withdraw: ");
double amountToWithdraw = scanner.nextDouble();
account.withDraw(amountToWithdraw);
System.out.println("You balance is now " + account.getBalance());
}
}
class Account{
double balance;
public Account(double initialBalance) {
balance = initialBalance;
}
public double getBalance(){
return balance;
}
public void withDraw(double amount) {
balance -= amount;
}
}
EDIT
Here's a suggestion. I see you have a SavingsAccount array. So you probably want multiple accounts. I also you that you're trying to access a specific account by account id in the actionPerformed if the checkB is pressed. What you should do then, if loop through the array and if the id is found, then use that account to do your work. Something like this
inputAcct_No = Integer.parseInt(JOptionPane.showInputDialog("Enter Account Number"));
SavingsAccount savings;
for (SavingsAccount account : SavingsAccounts){ <-- your array
if (acound.getId() == inputAcct_No){
savings = account;
}
}
// do something with savings
Now you can do something with that account because it is referencing the account in the array.
Its better to tell the exact issue you are facing , its difficult to check the complete code..
At a galance what i got is that in your SavingsAccount class getBalance() method you are simply subtracting and returning but there is no effect on the actual value of balance.
What i think you have to do balance-withdraw in your setWithdraw() method.

Categories