Is it possible to use a scanner this way? - java

Ok so, this is whats going on. I'm making a simple simple bank program.
This is what I want to do, notice the variables for my Account class (a1, a2, a3)
This works perfectly fine, but not for what I want to do.
In the switch cases, I want to be able to let the user input the name under the account and be able to edit it.
Now, I know if I were to basically do this:
Account AccountObject = new Account ();
balance.put (sc.nextLine(), AO.addFunds)
Then I would have separate users, but the funds would essentially all be the same. How would I make them separate*
I know once I figure out how to do this, I'll be set to move on to more complicated projects.
import java.util.Hashtable;
import java.util.Scanner;
class Data {
public static void main(String args[]) {
Hashtable<String, Double> balance = new Hashtable<String, Double>();
Scanner sc = new Scanner(System.in);
Scanner sa = new Scanner(System.in);
boolean quit = false;
boolean quit2 = false;
// Create account variables
Account a1 = new Account();
Account a2 = new Account();
Account a3 = new Account();
Account a4 = new Account();
Account a5 = new Account();
// Add funds to variables in Hashtable
balance.put(sc.nextLine(), a1.addFunds());
balance.put(sc.nextLine(), a2.addFunds());
balance.put(sc.nextLine(), a3.addFunds());
balance.put(sc.nextLine(), a4.addFunds());
balance.put(sc.nextLine(), a5.addFunds());
do {
System.out.println("Menu: \n 1: Check balance\n 2: Add funds\n 3: Withdraw funds\n 4: Quit");
int input = sa.nextInt();
switch (input) {
case 1:
System.out.println(balance.get(sc.nextLine()));
break;
case 2:
System.out.println(balance.put(sc.nextLine(), a1.addFunds()));
break;
case 3:
System.out.println(balance.put(sc.nextLine(), a1.withdrawFunds(sa.nextDouble())));
break;
case 4:
quit = true;
break;
}
} while(!quit);
System.out.println("Exiting menu");
}
}
Account class
import java.util.Scanner;
public class Account {
int balance;
String name;
public double addFunds() {
Scanner sa = new Scanner(System.in);
double amount = sa.nextDouble();
balance += amount;
return balance;
}
public String Acct(String names) {
Scanner sc = new Scanner(System.in);
name = names;
return name;
}
public double withdrawFunds(double amount) {
balance -= amount;
return balance;
}
public String toString() {
return String.format("Balance: %n", balance);
}
}

You should create an Account class, which is model for an account. I suggest you do not handle the user input inside the Account class.
Account class
public class Account {
private String name;
private int balance;
public Account(String name, int startBalance) {
this.name = name;
this.balance = startBalance;
}
public void addFunds(int amount) {
if (amount < 0) {
throw new IllegalArgumentException("Amount must be absolute");
}
this.balance += amount;
}
public void withdrawFunds(int amount) {
if (amount < 0) {
throw new IllegalArgumentException("Amount must be absolute");
}
else if (amount > this.balance) {
throw new IllegalArgumentException("You don't have that, so you cannot grab that.");
}
this.balance -= amount;
}
public String getName() {
this.name;
}
public int getBalance() {
return this.balance;
}
}
Now, if you want, you can create some accounts and add them to an ArrayList<Account>. I do not know why you would use a HashMap: if you have just a list with all Account objects, you have all information you need.
ArrayList<Account> accounts = new ArrayList<Account>();
Scanner sc = new Scanner(System.in);
You can implement your user input like something like:
private static ArrayList<Account> accounts = new ArrayList<Account>();
private static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
initializeSomeBankAccounts();
displayUI();
}
private static void initializeSomeBankAccounts() {
for (int i = 0; i < 2; i++) {
System.out.print("Insert " + (i > 0 ? "another " : "") + "account name: ");
String name = sc.nextLine();
System.out.print("Insert start balance: ");
int startBalance = sc.nextInt();
sc.nextLine();
// Create a new account using the user input
Account account = new Account(name, startBalance);
// Add the account to our list with accounts.
accounts.add(account);
}
}
public static void displayUI() {
boolean quit = false;
while (!quit) {
// Show a menu with the available actions
System.out.println("Menu: \n 1: Check balance\n 2: Add funds\n 3: Withdraw funds\n 4: Quit");
int action = sc.nextInt();
sc.nextLine();
Account account;
// Since we ask the user to insert a right account name, we can
// guarantee that the variable 'account' contains an Account
// object.
switch (action) {
case 1:
account = askAccount();
System.out.println(account.getBalance());
break;
case 2:
account = askAccount();
System.out.print("Amount: ");
int amount = sc.nextInt();
account.addFunds(amount);
break;
case 3:
account = askAccount();
System.out.print("Amount: ");
amount = sc.nextInt();
account.withdrawFunds(amount);
break;
case 4:
quit = true;
break;
}
}
}
private static Account askAccount() {
System.out.println("Which account? ");
Account account = null;
boolean accountFound = false;
// Now the user has to input a valid account name, we're going to
// search for that account name in the list. If it is found, we
// have the whole Account object stored into the variable 'account'.
// Otherwise, if it is not found, then we repeat to ask to insert
// an account name, until a account name is given which is present
// in our list.
while (!accountFound) {
String accountName = sc.nextLine();
account = searchAccount(accountName);
if (account == null) {
System.out.println("Account not found. Insert another account:");
}
else {
accountFound = true;
}
}
return account;
}
/**
* Searches an account from our list of all accounts.
*
* #param name The name to search for.
* #return The account if found, or null otherwise.
*/
private static Account searchAccount(String name) {
for (Account account : accounts) {
if (account.getName().equals(name)) {
return account;
}
}
return null;
}
I also got a few suggestions:
You have some variables which are not used, i.e. quit2. You might want to remove them.
As far as I know, you do not need to have two Scanners; one is sufficient, since you can call both nextLine() and nextInt() on the same Scanner.
You have variables starting with an uppercase character, i.e. AccountObject. In Java, it is allowed, but the Java Naming Conventions prescribe that one should start variables with a lowercase letter.
You are using the class Hashtable, but it is recommended to use HashMap<Key, Value>.

Related

How to access a method from another if it has arguments

I want to know how I can access a call a method when it has an arraylist as an argument from an another class.
import java.util.*;
class Business
{
public static void main()
{
Scanner si = new Scanner(System.in);
int t = 0;
System.out.println("Enter--");
System.out.println("1 to add a account");
System.out.println("2 to check the balance");
int d = si.nextInt();
if(d==1)
{
add_account();
}
if(d == 2)
{
check();
}
}
public static void add_account()
{
Scanner si = new Scanner(System.in);
int min = 1000;
int max = 9999;
int acn;
List<Double> ac = new ArrayList<>();
List<Integer> cl = new ArrayList<>();
List<String> al = new ArrayList<>();
System.out.println("Enter the name of the account user");
al.add(si.next());
System.out.println("Enter the amount user has deposited");
cl.add(si.nextInt());
ac.add(Math.floor(Math.random() * (max - min + 1) + min));
System.out.println("Please re-enter your name");
String name = si.next();
acn = al.indexOf(name);
System.out.println("Your account number is "+acn);
System.out.println("Your account password is "+ac.get(acn));
System.out.println(ac);
main();
}
public static void check(List<Double> ac)
{
Scanner si = new Scanner(System.in);
System.out.println("Enter the account number whoose you want to check the balance");
int c = si.nextInt();
System.out.println(ac);
}
}
Here, I want to know how to access the check method, I think I have to write in something in the brackets . If so, can you tell me what to write, if not please tell how can I access the check method from the main method.
The simplest solution would be to move the 3 lists storing the user data from the add_account to the class level as static variables like this:
public class Business {
private static List<Double> ac = new ArrayList<>();
private static List<Integer> cl = new ArrayList<>();
private static List<String> al = new ArrayList<>();
public static void main() {
//...
}
public static void add_account() {
//...
}
public static void check() {
//...
}
}
This way you can remove the input parameter from the check method and just access the class level ac list.
However a better solution would be to model the account as dedicated class like
public class Account {
String name;
Integer balance;
String password;
// getters + setters
}
and store them in a Map where the key is the accounts name/id
private static Map<String, Account> accounts = new HashMap<>();
I'm trying to understand the code
public static void check(List<Double> ac)
{
Scanner si = new Scanner(System.in);
System.out.println("Enter the account number whoose you want to check the balance");
int c = si.nextInt();
System.out.println(ac);
}
here you declare the method with a parameter of a List. So you cannot call this method without giving a parameter inside. If you want to search the account inside of the method, you can just remove the parameter of the method, get the account and display it.
public static void check() //parameter removed
{
Scanner si = new Scanner(System.in);
System.out.println("Enter the account number whoose you want to check the balance");
int c = si.nextInt(); // get the account number
List<Double> account = new ArrayList<Double>();
// ... some operation
System.out.println(account.toString());
}
After that inside of the main method, you can call this method
public static void main()
{
Scanner si = new Scanner(System.in);
int t = 0;
System.out.println("Enter--");
System.out.println("1 to add a account");
System.out.println("2 to check the balance");
int d = si.nextInt();
if(d==1)
{
add_account();
}
if(d == 2)
{
check();
}
}

Java getter setter failing to store value

I'm trying to answer these questions.
The New Account option should implement the following:
Input client details: name, address, birthday, and contact number
Input the initial deposit of not less than PhP5,000
Generate a four-digit account number randomly
The Balance Inquiry option should implement the following:
Input the account number and validate
If the account number is valid, display the client name and current
balance
I've tried coding the New Account option with setter methods in it and also generates a four-digit number randomly that I can use to input it in the Balance Inquiry option that has getter methods but it displays empty. I tried debugging it and the variables return empty after exiting the if statement.
Class with the main method, displayMainMenu() for the options, newAccount() and fourRandomNumber().
public class ClientUgang {
public static void main(String[] args) {
displayMainMenu();
}
public static void displayMainMenu() {
SavingsAccountUgang savingsAccount = new SavingsAccountUgang();
int option = 0;
while (option != 7) {
Scanner scan = new Scanner(System.in);
System.out.println("JBank Main Menu");
System.out.println("[1] New Account");
System.out.println("[2] Balance Inquiry");
System.out.println("[3] Deposit");
System.out.println("[4] Withdraw");
System.out.println("[5] Client Profile");
System.out.println("[6] Close Account");
System.out.println("[7] Exit");
option = scan.nextInt();
if (option == 1) {
newAccount();
}
if (option == 2) {
savingsAccount.balanceInquiry();
}
}
}
public static void newAccount() {
Scanner scan = new Scanner(System.in);
SavingsAccountUgang savingsAccount = new SavingsAccountUgang();
System.out.print("Name: ");
String name = scan.nextLine();
System.out.print("Address: ");
String address = scan.nextLine();
System.out.print("Birthday: ");
String birthday = scan.nextLine();
System.out.print("Contact number: ");
String contactNumber = scan.nextLine();
savingsAccount.setAccountName(name);
savingsAccount.setAddress(address);
savingsAccount.setBirthday(birthday);
savingsAccount.setContactNumber(contactNumber);
int deposit = 0;
while (deposit < 5000) {
System.out.print("Initial deposit(not less than Php5000): ");
deposit = scan.nextInt();
}
savingsAccount.setBalance(deposit);
int fourDigitNumber = fourRandomNumber(1000, 9000);
savingsAccount.setAccountNo(fourDigitNumber);
System.out.println("Your Account Number: " + fourDigitNumber);
System.out.println();
}
public static int fourRandomNumber(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
}
The Class where my balanceInquiry() method is. My setter and getter method for accountName is in BankAccountUgang class.
public class SavingsAccountUgang extends BankAccountUgang {
private int accountNo;
private double balance;
public SavingsAccountUgang() {
}
public int getAccountNo() {
return accountNo;
}
public void setAccountNo(int accountNo) {
this.accountNo = accountNo;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public void balanceInquiry() {
Scanner scan = new Scanner(System.in);
int accountNumber = 0;
do {
System.out.print("Enter Account Number: ");
accountNumber = scan.nextInt());
} while (accountNumber != getAccountNo());
System.out.println(getAccountName());
System.out.println(getBalance());
System.out.println();
}
}
I expect the setter methods to work so that I can call the getter methods.
JBank Main Menu
[1] New Account
[2] Balance Inquiry
[3] Deposit
[4] Withdraw
[5] Client Profile
[6] Close Account
[7] Exit
1
Name: John
Address: World
Birthday: Aug 2019
Contact number: 123 1234
Initial deposit(not less than Php5000): 5000
Your Account Number: 6810
JBank Main Menu
[1] New Account
[2] Balance Inquiry
[3] Deposit
[4] Withdraw
[5] Client Profile
[6] Close Account
[7] Exit
2
Enter Account Number: 6810
Enter Account Number: BUILD STOPPED (total time: 27 seconds)
There are a lot of issues with your code.
To fix that 1 way is below:
Return a new saving account from the newAccount method, so change the return type to:
public static SavingsAccountUgang newAccount() {
// Your existing code
return savingsAccount;
}
Then in your displayMainMenu() method save this account if the user enters 1 as an input and later use that instance to show the balance:
public static void displayMainMenu() {
SavingsAccountUgang savingsAccount = null // don't create object here as you are doing
// Your code
if (option == 1) {
savingsAccount = newAccount();
}
if (option == 2) {
if(savingsAccount == null) {
// throw exception or whatever you want to do.
}
savingsAccount.balanceInquiry();
}
}
The SavingsAccountUgang instance in your newAccount() method is a local variable and therefore only visible to this method.
If you want to use it outside your method you have to return or declare it outside of your method.
Well, the setBalance() method requires an argument type double, but you send a type int, but it's not a reason for a mistake. Also, you should use this in a statement like this one:
while (accountNumber != this.getAccountNo());

How to make ArrayList or other to work for finding a specific data in the stored list

I have written a code that takes input as Account details and displays the details by using ArrayList. I however want the list to fetch a particular/specific account details only for a data. Lets say i stored account number details for 127783 and 127784. Now i want only account number 127783 details. How do i fetch that using arrayList. If it doesn't happen with an ArrayList then what to use.
package com.techlabs.account;
import java.util.ArrayList;
import java.util.Scanner;
public class AccountMenu {
static int accountno;
String name;
double balance;
ArrayList a = new ArrayList();
public AccountMenu() {
Scanner in = new Scanner(System.in);
System.out.println("Enter the number for the following menu :1. Open Account 2. Show Account details "
+ "3.Retrieve details by Searching Account Number 4. Exit");
int number = in.nextInt();
while (!(number == 4)) {
if (number == 1) {
System.out.println("Enter the Account no.");
accountno = in.nextInt();
a.add(accountno);
System.out.println("Enter the name");
name = in.next();
a.add(name);
System.out.println("Enter the Balance");
balance = in.nextDouble();
a.add(balance);
}
if (number == 2) {
System.out.println("Account details are :");
for (Object b : a) {
System.out.println(b);
}
}
if (number == 3) {
System.out.println("Enter the account number");
accountno=in.nextInt();
if (a.contains(accountno)) {
System.out.println(a);
}
}
if (number == 4) {
System.out.println("Exit");
}
System.out.println("Enter the option :1. Open Account 2. Show Account details 3.Retrieve details by Searching Account Number and 4. Exit again");
number = in.nextInt();
}
}
public static void main(String[] args) {
AccountMenu am = new AccountMenu();
}
}
Instead of dropping everything into a list of objects I would create a class for storing account details (with members of account number, name, balance).
I would store these in a Map < Integer, Account >. When you need a specific account's detail you can say map.get(accountNumber) and you will get back your specific Account instance.
Edit:
A wrapper class to hold Account details:
public Class AccountDetails{
public final int accountNumber;
public final String name;
public final int balance;
constructor
}
Instead of arraylist a should be:
Map<Integer, AccountDetails> a = new HashMap<>();
Where your create new accounts:
AccountDetails accountDetails = new AccountDetails(accountno, name, balance);
a.put(accountno, accountDetails)
Where you print details you should ask for the account number from the user, and after that:
System.out.println(a.get(accountno));
Of course to see something meaningful you should write a toString() method for the AccountDetails class.
I found a lot of errors relatying to POO in your code. Please check the code below and study OO concepts. I created a private class to represent the accounts. That way you can have an arraylist of account objects.
import java.util.ArrayList;
import java.util.Scanner;
public class JavaApplication5 {
private static final class Account {
int accountno;
String name;
double balance;
#Override
public String toString() {
return "Account{" + "accountno=" + accountno + ", name=" + name + ", balance=" + balance + '}';
}
public void deposit(double amount){
balance = balance + amount;
}
void withdraw(double amount){
balance = balance-amount;
}
}
public static void AccountMenu() {
ArrayList<Account> a = new ArrayList();
Scanner in = new Scanner(System.in);
System.out.println("Enter the number for the following menu :1. Open Account 2. Show Account details "
+ "3.Retrieve details by Searching Account Number 4. Exit");
int number = in.nextInt();
while (!(number == 4)) {
switch (number) {
case 1: {
Account c = new Account();
System.out.println("Enter the Account no.");
c.accountno = in.nextInt();
System.out.println("Enter the name");
c.name = in.next();
System.out.println("Enter the Balance");
c.balance = in.nextDouble();
a.add(c);
break;
}
case 2: {
System.out.println("Account details are :");
for (Account b : a) {
System.out.println(b);
}
break;
}
case 3: {
System.out.println("Enter the account number");
int accountno = in.nextInt();
for (Account account : a) {
if (account.accountno == accountno) {
System.out.println(account);
}
}
break;
}
case 4:
System.out.println("Exit");
}
System.out.println("Enter the number for the following menu :1. Open Account 2. Show Account details "
+ "3.Retrieve details by Searching Account Number 4. Exit");
number = in.nextInt();
}
}
public static void main(String[] args) {
AccountMenu();
}
}

How to perform arithmetic operation between the objects written in a file?

In my program, users enter values and those get stored in arrayList. ArryList objects are written into a file. I have used file-i/o, object-i/o stream for writing and readin in file.Now I want to perform addition and subtraction among the objects (int or double). That is withdrawing money from one account should be added with another account, and their value must be subtracted and added with the particular acount's amount. And finally I want that value must be updated so that it can print out and show the current status. How could I do that?
This is the main class:
public class BankApp_Assignment {
//static int numOfAcc = 0;
public static void main(String[] args) {
System.out.println("WELCOME TO OUR BANK!\n\n");
List<BankAccount> bankAccounts = new ArrayList<BankAccount>();
List<BankAccount> bankAccounts2 = new ArrayList<BankAccount>();
ReaderWriter rw=new ReaderWriter();
while (true) {
System.out.println("Choose your option:\n"
+ "1. Create new account\n"
+ "2. Deposit/withdraw\n"
+ "3. View One account\n"
+ "4. Deleting an account\n"
+ "5. View all the accounts\n"
+ "6. Return to menu\n");
System.out.println("*************\n"
+ "************");
option1 = sc.nextInt();
sc.nextLine();
//switch-case starts
switch (option1) {
case 1:
//create account
BankAccount bankAcc = new BankAccount();
System.out.println("Enter Full Name:");
bankAcc.setName(sc.nextLine());
System.out.println("Choose an Account Number:");
bankAcc.setAccNum(sc.nextInt());
System.out.println("Choose the initial amount:");
bankAcc.setInitiateAmount(sc.nextDouble());
//adding those into the arrayList
bankAccounts.add(bankAcc);
rw.writeToFile(bankAccounts);
System.out.println("-------------\n"
+ "-------------");
break;
case 2:
bankAccounts2=(List<BankAccount>)rw.readFromFile();
//First displaying the current accouns info
System.out.println("Name \tAccount No \tInitial Amount");
for (BankAccount bankAccount : bankAccounts2) {
System.out.println(bankAccount);
}
System.out.println("\t\t.........\n"
+ "\t\t.........");
System.out.println("To transfer money within the bank accounts enter 1\n"
+ "To deposit/withdraw money in the same account enter 2");
option2 = sc.nextInt();
sc.nextLine();
//inner switch-case starts
switch (option2) {
case 1:
/*
BankAccount is the class for setter and getter
bankAccounts2 is the arrayList for reading objects from file
*/
bankAccounts2 = (List<BankAccount>) rw.readFromFile();
BankAccount fromAcc = null;
BankAccount toAcc = null;
System.out.println("Enter the account number you want to withdraw from:");
withdraw_accNum = sc.nextInt();
System.out.println("Enter the amount you want to withdraw:");
withdraw_amount = sc.nextDouble();
System.out.println("Enter the account number you want to deposit to:");
deposit_accNum = sc.nextInt();//the deposit amount is alwyas the same as withdraw_amount
//find the matching acc number:withdraw_accNum
for (BankAccount listItemsFirst : bankAccounts2) {
//if the withdraw acc num matches with the given one
if (listItemsFirst.getAccNum() == withdraw_accNum) {
//store it
fromAcc = listItemsFirst;
break;
}
}
//find the matching acc number: deposit_accNum
for (BankAccount listItemsSec : bankAccounts2) {
//if the withdraw acc num matches with the given one
if (listItemsSec.getAccNum() == deposit_accNum) {
//store it
toAcc = listItemsSec;
break;
}
}
//if the withdraw amount is bigger than the current balance
if (withdraw_amount > fromAcc.getInitialAmount()) {
System.out.println("Withdrawing Amount was bigger than the Initial amount.\nChoose the menu again. .");
break;
}
//subtracting and adding the withdrawn amount
fromAcc.setInitiateAmount(fromAcc.getInitialAmount() - withdraw_amount);
toAcc.setInitiateAmount(toAcc.getInitialAmount() + withdraw_amount);
System.out.println("DONE!\t print them out to see the current status.");
System.out.println("");
break;
case 2://deposit/withdraw money in the same accounts
bankAccounts2=(List<BankAccount>)rw.readFromFile();
BankAccount fromAcc_SameAcc = null;
BankAccount toAcc_SameAcc = null;
System.out.println("Enter the account number you want to deposit or withdraw from:");
//read the accNum
depOrWithAccountNum = sc.nextInt();
System.out.println("Enter the amount (To withdraw enter a negative value)");
//read the amount
depOrWithAmount = sc.nextDouble();
//checking the matching account number in arrayList
for (BankAccount listItemsThird : bankAccounts2) {
if (listItemsThird.getAccNum() == depOrWithAccountNum) {
fromAcc_SameAcc = listItemsThird;
break;
}
}
if (depOrWithAmount - 1 < fromAcc_SameAcc.getInitialAmount()) {
System.out.println("Withdraw amount is bigger than the current amount.\nChoose the menu again. .");
break;
}
if (depOrWithAmount < 0) {//the amount is negative
fromAcc_SameAcc.setInitiateAmount(fromAcc_SameAcc.getInitialAmount() + depOrWithAmount);
} else {
fromAcc_SameAcc.setInitiateAmount(fromAcc_SameAcc.getInitialAmount() + depOrWithAmount);
}
break;
}
//inner switch-case ends
System.out.println("\n\n");
break;
case 3:
//View One account
bankAccounts2=(List<BankAccount>)rw.readFromFile();
BankAccount viewOneAccountNum = null;
System.out.println("Enter the account number you want to see:");
viewOneAcc = sc.nextInt();
System.out.println("Name\tAccount No\tInitial Amount");
for (BankAccount viewOneAccountProperty : bankAccounts2) {
if (viewOneAccountProperty.getAccNum() == viewOneAcc) {
//viewOneAccountNum=viewOneAccountProperty;
viewOneAccountNum = viewOneAccountProperty;
System.out.println(viewOneAccountNum);
}
System.out.println("");
}
break;
case 4:
bankAccounts2=(List<BankAccount>)rw.readFromFile();
//BankAccount AccToDel = null;
//Deleting an account
Iterator<BankAccount> it = bankAccounts2.iterator();
System.out.println("Enter the account you want to delete:");
deleteAcc = sc.nextInt();
while (it.hasNext()) {
BankAccount next = it.next();
if (next.getAccNum() == deleteAcc) {
it.remove();
}
}
rw.writeToFile(bankAccounts2);
break;
case 5:
//View all the accounts/printing them out
bankAccounts2=(List<BankAccount>)rw.readFromFile();
System.out.println("Name\tAccount No\tInitial Amount");
for (BankAccount bankAccount : bankAccounts2) {
System.out.println(bankAccount);
}
System.out.println("\n\n");
break;
case 6:
//Quit
return;
}
//switch-case ends
}
}
}
ReaderWriter:
public class ReaderWriter{
public void writeToFile(List<BankAccount> accounts){
try {
FileOutputStream fos=new FileOutputStream("C:\\Users\\Documents\\NetBeansProjects\\BankFile_assignment.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(accounts);//take the arrayList
oos.flush();
oos.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public List<BankAccount> readFromFile(){
List<BankAccount>readData=null;
try {
FileInputStream fis=new FileInputStream("C:\\Users\Documents\\NetBeansProjects\\BankFile_assignment.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
//make an arrayList to get those object back
//arrayList
readData=(List<BankAccount>)ois.readObject();
ois.close();
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
//return readData;
return readData;
}
}
BankAccount:
package bankapp_assignment;
import java.io.Serializable;
public class BankAccount implements Serializable{
private String name;
private int accNum;
private double initiateAmount;
//constructor
public BankAccount() {
this.name = null;
this.accNum = 0;
this.initiateAmount = 0;
}
public void setName(String name) {
this.name = name;
}
public void setAccNum(int accNum) {
this.accNum = accNum;
}
public String getName(String name){
return name;
}
public int getAccNum() {
return accNum;
}
public void setInitiateAmount(double initiateAmount) {
this.initiateAmount = initiateAmount;
}
public double getInitialAmount(){
return initiateAmount;
}
#Override
public String toString() {
return name + "\t\t" + accNum + "\t\t" + initiateAmount;
}
}
you should refactor whole main method. If I were you, I would use
main only to lunch program, rest process in other methods. This way you would be able to use class fields all over program, and divide code into many methods.
You should divide main beetween other methods, to at least method
per action, exemple:
case 1:
createAccount();
break;
(...)
public void createAccount(){
code from your swich case 1
}
etc. You can still use swich control, but should replece logic code to another method.
When i run your code, input/output didn't work. Were you able to
save/load file? I had to chage:
File file = new File("//file path");
FileOutputStream fos = new FileOutputStream(file);
ObjectOutput oos = new ObjectOutputStream(fos);
Same with input. Then it worked.
Now, we will try to deal with operation on BankAccounts from files. I change a little bit your code from case2/case2: deposit/withdraw, lets look at it:
bankAccounts2 = rw.readFromFile(); // loading list from file
BankAccount edited = new BankAccount(); // creating new object
System.out.println("Enter the account number you want to deposit or withdraw from:");
double input = sc.nextInt(); // you don't need to create new variable every time you take input form user
for(BankAccount account : bankAccounts2){ // every account in list
if(account.getAccNum() == input) edited = account; // if acccNum match, give edited reference to chosen account
}
System.out.println("Enter the amount (To withdraw enter a negative value)");
input = sc.nextDouble();
double result = edited.getInitialAmount() + input; // result of operation
if(result < 0){ // check if there is enough money on account
System.out.println("Withdraw amount is bigger than the current amount.\nChoose the menu again. .");
break;
}else{
edited.setInitiateAmount(result); // if there is, set new value
}
rw.writeToFile(bankAccounts2); // save file
You can implement another operation in similar style. But still, you should consider dividing main into other methods, adding class fields, etc.
EDIT:
For question in comments.
Because you use positive numbers for deposit, and negative numbers for withdraw, the operation on initialAmount will be always the same: initialAmount + input (if negative, is will subtract from amount), so you can treat it like an one case in your code. In your code you use this line twice:
fromAcc_SameAcc.setInitiateAmount(fromAcc_SameAcc.getInitialAmount() + depOrWithAmount);
so you already could merge both cases into one, to avoid unnecessary repetitions. So only case when action will differ, is when there is not enough money on a account, you check it by:
if (depOrWithAmount - 1 < fromAcc_SameAcc.getInitialAmount())
but i think i will not work, because in withdraw operation depOrWithAmount is in negative numbers, so it will always be smaller than fromAcc_SameAcc.getInitialAmount(). You can use:
if (depOrWithAmount < 1 - fromAcc_SameAcc.getInitialAmount())
(but i think it is not too readable) or:
if (Math.abs(depOrWithAmount) > fromAcc_SameAcc.getInitialAmount()){}
to compare absolute value of input with initialAmout. However i used:
double result = edited.getInitialAmount() + input;
if(result < 0){...}
because it gives me result variable, which I can reuse if there is enough money, to gives new value to initialAmount. And if result is negative, it means that withdraw amount was bigger than initialAmount, so ther is no enough monay to withdraw.
I hope you found something useful in my post.

bank account client in java with multiple classes

I am trying to make a bank account program, but I cannot figure out how to get all my variables visible to every class that I have, or how to make the withdrawal and deposit methods of my code visible. Can anyone look at my code and tell me what is wrong? I only want input and output in the client class.
Thanks
Client Class
public class Client {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your Name: ");
String cusName = input.nextLine();
System.out.println("Enter Account Type: ");
String type = input.next();
System.out.println("Enter Initial Balance: ");
int bal = input.nextInt();
BankAccount b1 = new BankAccount(cusName, num, type, bal);
int menu;
System.out.println("Menu");
System.out.println("1. Deposit Amount");
System.out.println("2. Withdraw Amount");
System.out.println("3. Display Information");
System.out.println("4. Exit");
boolean quit = false;
do {
System.out.print("Please enter your choice: ");
menu = input.nextInt();
switch (menu) {
case 1:
b1.deposit();
break;
case 2:
b1.withdraw();
System.out.println("Current Account Balance=" + Balance);
System.out.print("Enter withdrawal amount:");
amount = input.nextInt();
break;
case 3:
b1.display();
break;
case 4:
quit = true;
break;
}
} while (!quit);
}
}
Money Class
public class Money
{
static int accountNumber, Balance, amount;
Scanner input = new Scanner(System.in);
static String name, actype;
public int deposit() {
System.out.print("Enter depost amount:");
amount = input.nextInt();
if (amount < 0) {
System.out.println("Invalid");
return 1;
}
Balance = Balance + amount;
return 0;
}
int withdraw() {
if (Balance < amount) {
System.out.println("Not enough funds.");
return 1;
}
if (amount < 0) {
System.out.println("Invalid");
return 1;
}
Balance = Balance - amount;
return 0;
}
}
BankAccount Class
class BankAccount {
Scanner input = new Scanner(System.in);
static String name, actype;
static int bal, amt;
Random randomGenerator = new Random();
int accNo = randomGenerator.nextInt(100);
BankAccount(String name, int accNo, String actype, int bal) {
this.name = name;
this.accNo = accNo;
this.actype = actype;
this.bal = bal;
}
void display() {
System.out.println("Name:" + name);
System.out.println("Account No:" + accNo);
System.out.println("Balance:" + bal);
}
void dbal() {
System.out.println("Balance:" + bal);
}
}
Add Money to your BankAccount and create a getter method as:
class BankAccount {
Scanner input = new Scanner(System.in);
static String name, actype;
static int bal, amt;
Random randomGenerator = new Random();
int accNo = randomGenerator.nextInt(100);
Money money;
BankAccount(String name, int accNo, String actype, int bal) {
this.name = name;
this.accNo = accNo;
this.actype = actype;
this.bal = bal;
this.money = new Money();
}
public Money getMoney(){
return this.money;
}
.....
}
Use bankaccount.getMoney() to invoke deposit and withdraw as :
b1.getMoney().deposit();
b1.getMoney().withdraw();
In addition, I would advice to make the Money class attributes e.g. amount, accntType... non-static and set through through a constructor. Static variables are associated with class definition and hence you won't be abl to maintain them per Bank Account.
I'm not going to answer this question for you. Instead, I'm going to recommend that you read a bit more about Java programming concepts that will explain it to you, by default.
Here is one on encapsulation, which is the main concept that you're asking about
This is a great book on how to write code well, including things like keeping methods short
In particular, your main method should be broken into smaller pieces
Here's a stack overflow question that talks about it if you don't want to buy the book.
If you don't want to read any of these links, #YogendraSingh answered this question really well, use that answer.
Attributes to an object shouldn't be static, for example your "name, actype, bal and amt". Also I think your money class should exist and those methods could be in a bank account (you deposit/withdraw from a bank account).

Categories

Resources