I want to withdraw some money after depositing some but what I get is an error..why? for example, I deposit 100 and after that I want to withdraw 90, but all I got is an error. Another is, after depositing 100, I want to print my current balance but it prints (0) zero. why? please help.
Main Class
import java.awt.HeadlessException;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Banko{
private static String name;
private static double bal;
private static double withdraw;
private static BankAccount myAccount;
public static void main(String args[]) {
name = JOptionPane.showInputDialog(null, "Enter your name: ");
String num;
int pin;
num = JOptionPane.showInputDialog("Enter your pin number: ");
pin = Integer.parseInt(num);
JOptionPane.showMessageDialog(null, "Login Success\n" + "Name : " + name + "\n" + "Pin Number : " + pin);
BankAccount myAccount = new BankAccount(withdraw, name);
int rc = getRC();
processor(num, rc);
}
private static int getRC(){
String[] buttons = { "Deposit", "Withdraw", "Print Balance", "Exit" };
int rc = JOptionPane.showOptionDialog(
null,
"What would you like to do?",
"Confirmation",
JOptionPane.INFORMATION_MESSAGE,
0,
null,
buttons,
buttons[2]);
return rc;
}
private static void processor(String num, int rc) {
switch(rc) {
case 0:
processDeposit(num, rc);
break;
case 1:
processWithdraw(num, myAccount, rc);
break;
case 2:
processBalance(num, rc);
default:
processExit(rc);
break;
}
}
private static void processExit(int rc) throws HeadlessException {
if(rc == -1) {
JOptionPane.showMessageDialog(null, "\nThank you. Have a good day!");
System.exit(0);
}
}
private static void processDeposit(String num, int rc) throws HeadlessException, NumberFormatException {
int deposit;
String dep = JOptionPane.showInputDialog("How much would you like to deposit?\n\t$ ");
deposit = Integer.parseInt(num);
JOptionPane.showMessageDialog(null, "You have deposited $" + dep + " into the account of " + name);
String proceeds = JOptionPane.showInputDialog(null, "\nWould you like to do another transaction? (Y/N)");
if(proceeds.equalsIgnoreCase("y")) {
rc = getRC();
processor(num, rc);
} else {
processExit(-1);
}
}
private static void processBalance(String num, int rc) throws HeadlessException {
JOptionPane.showMessageDialog(null, "The balance in the account of " + name + " with the pin number " + num
+ " is $" + bal);
String proceeds = JOptionPane.showInputDialog(null, "\nWould you like to do another transaction? (Y/N)");
if(proceeds.equalsIgnoreCase("y")) {
rc = getRC();
processor(num, rc);
} else {
processExit(-1);
}
}
private static void processWithdraw(String num, BankAccount myAccount, int rc) throws HeadlessException, NumberFormatException {
double withdraw;
String with = JOptionPane.showInputDialog("How much would you like to withdraw?\n\t$");
withdraw = Integer.parseInt(num);
if(bal - withdraw > 0) {
myAccount.withdraw(withdraw);
JOptionPane.showMessageDialog(null, "You have withdrawn $" + withdraw + " from the account of " + name
+ ". The new balance is: " + myAccount.getBalance());
} else {
JOptionPane.showMessageDialog(
null,
"Sorry, you have insufficient funds for this operation. Your existing balance is $"
+ myAccount.getBalance());
}
String proceeds = JOptionPane.showInputDialog(null, "\nWould you like to do another transaction? (Y/N)");
if(proceeds.equalsIgnoreCase("y")) {
rc = getRC();
processor(num, rc);
} else {
processExit(-1);
}
}
}
Base Class:
import java.util.Scanner;
public class BankAccount {
private double balance;
private String name;
public BankAccount(double b, String n) {
this.balance = b;
this.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;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Good Experiment. Only minor mistakes.
Unnecessary variable bal since you have balance in account itself
Must use object myAccount everywhere.
changes in deposit
deposit = Integer.parseInt(dep);
JOptionPane.showMessageDialog(null, "You have deposited $"
+ dep + " into the account of " + name);
myAccount.setBalance(myAccount.getBalance() + deposit);
withdraw
withdraw = Integer.parseInt(with);
if (myAccount.getBalance() - withdraw > 0) {
getBalance
JOptionPane.showMessageDialog(null, "The balance in the account of "
+ name + " with the pin number " + num
+ " is $" + myAccount.getBalance());
You are declaring a new BankAccount instance, instead of using the static variable:
public static void main(String args[]) {
// ...
myAccount = new BankAccount(withdraw, name);
int rc = getRC();
processor(num, rc);
}
Related
I was working on a Uni project for the end of the semester. The program is a simple bank system. My issue is that when the program first launches it creates a "Log" folder. Then when an account object is created using a Constructor a new txt file is created in the folder with the name of the account holder. Up until here I have managed to do it.
The issue is that when closing the program via the option menu but before closing the program, all the details from all the created objects (which are stored in a array) are written in their respective files following the order they are stored in the object array but on the first run the files are created but nothing is written in them.
Then on the 2nd run if I close the program again the details are written correctly. Can I have some suggestions please I could not find anything regarding this online?
import java.util.Scanner;
import java.io.*;
public class FileManagement {
static String pathnameFile = "src\\Log";
static File directory = new File(pathnameFile);
static String[] allFiles = directory.list();
public static void createFolder() {
File logFile = new File(pathnameFile);
if (!logFile.exists()) {
logFile.mkdir();
}
}
public static void writeFiles() throws IOException {
FileWriter writer;
for (int i = 0; i < allFiles.length; i++) {
writer = new FileWriter(pathnameFile + "\\" + allFiles[i]);
writer.write("accountName= " + eBanking.accounts[i].getAccountName() + "\n");
writer.write("PIN= " + eBanking.accounts[i].getPIN() + "\n");
writer.write("balance= " + Integer.toString(eBanking.accounts[i].getBalance()) + "\n");
writer.write("Object ID stored in RAM= " + eBanking.accounts[i].toString() + "\n");
writer.close();
}
}
//original method
/*public static void readFiles() {
Scanner reader;
for (int i = 0; i < allFiles.length; i++) {
reader = new Scanner(pathnameFile + allFiles[i]);
}
}*/
//My solution
public static void readFiles() throws IOException{
if(directory.exists() == false || allFiles == null) {
return;
}
Scanner reader;
File currentFile;
String[] data = new String[4];
for(int i = 0; i < allFiles.length; i++) {
currentFile = new File(pathnameFile + "\\" +allFiles[i]);
reader = new Scanner(currentFile);
int count = 0;
while(reader.hasNextLine()) {
if(!reader.hasNext()) {
break;
}
reader.next();
data[count] = reader.next();
count++;
}
reader.close();
String accountName = data[0];
String PIN = data[1];
int balance = Integer.parseInt(data[2]);
eBanking.accounts[i] = new eBanking(accountName, PIN, balance);
}
}
}
import java.util.Scanner;
import java.io.*;
public class App {
public static eBanking currentAccount;
public static void mainMenu() throws Exception{
while (true) {
Scanner input = new Scanner(System.in);
System.out.println("""
--------------------------------------------------------
1. Log in
2. Register
0. Exit.
--------------------------------------------------------
""");
int menuOption = input.nextInt();
switch (menuOption) {
case 1 -> {
System.out.println("Please enter your account name and PIN below.");
System.out.print("Account name: ");
String accountName = input.next();
System.out.print("PIN: ");
String PIN = input.next();
System.out.println();
for (int i = 0; i < eBanking.accounts.length; i++) {
if (accountName.equals(eBanking.accounts[i].getAccountName()) && PIN.equals(eBanking.accounts[i].getPIN())) {
eBanking.accounts[i].welcome();
currentAccount = eBanking.accounts[i];
break;
}
}
menu();
}
case 2 -> {
System.out.println("Please enter the account name, PIN and inital balance of your new account.");
System.out.print("Account name:");
String accountNameRegister = input.next();
System.out.print("PIN: ");
String registerPIN = input.next();
System.out.print("Initial balance: ");
int initialBalance = input.nextInt();
currentAccount = new eBanking(accountNameRegister, registerPIN, initialBalance);
menu();
}
default -> {
FileManagement.writeFiles();
System.exit(0);
}
}
}
}
public static void menu() {
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("""
--------------------------------------------------------
1. Show your balance.
2. Withdraw money.
3. Deposit money.
4. Change your PIN.
5. Transfer money to another person.
0. Back.
--------------------------------------------------------
""");
int menuOption = input.nextInt();
switch (menuOption) {
case 1 -> {
currentAccount.showBalance();
}
case 2 -> {
System.out.println("Please enter the amount you want to withdraw: ");
int withdrawAmount = input.nextInt();
currentAccount.withdraw(withdrawAmount);
}
case 3 -> {
System.out.println("Please enter the amount you want to deposit: ");
int depositAmount = input.nextInt();
currentAccount.deposit(depositAmount);
}
case 4 -> {
currentAccount.changePIN();
}
case 5 -> {
System.out.println("Please enter the amount you want to send: ");
int amount = input.nextInt();
System.out.println("Please enter the account number you want to send the money to: ");
String transferAccount = input.next();// Me nextLine(); duhet ta shkruaj 2 here qe ta marri, duke perdor next(); problemi evitohet (E kam hasur edhe tek c++ kete problem)
System.out.println("The amount of money is completed");
currentAccount.transfer(amount, transferAccount);
}
case 0 -> {
return;
}
default -> {
System.out.println("Please enter a number from the menu list!");
}
}
}
}
public static void main(String[] args) throws Exception {
FileManagement.createFolder();
FileManagement.readFiles();
mainMenu();
}
}
import java.util.Scanner;
import java.io.*;
public class eBanking extends BankAccount {
// Variable declaration
Scanner input = new Scanner(System.in);
private String accountName;
private String accountID;
public static eBanking[] accounts = new eBanking[100];
// Methods
public String getAccountName() {
return accountName;
}
public void welcome() {
System.out.println("---------------------------------------------------------------------------------------");
System.out.println("Hello " + accountName + ". Welcome to eBanking! Your account number is: " + this.accountID);
}
public void transfer(int x, String str) {
boolean foundID = false;
withdraw(x);
if (initialBalance == 0) {
System.out.println("Transaction failed!");
} else if (initialBalance < x) {
for(int i = 0; i < numberOfAccount; i++) {
if (str.equals(accounts[i].accountID)) {
accounts[i].balance += initialBalance;
System.out.println("Transaction completed!");
foundID = true;
}
}
if (foundID = false) {
System.out.println("Account not found. Transaction failed. Deposit reimbursed");
this.balance += initialBalance;
return;
}
} else {
for(int i = 0; i <= numberOfAccount; i++) {
if (str.equals(accounts[i].accountID)) {
accounts[i].balance += x;
System.out.println("Transaction completed!");
foundID=true;
return;
}
}
if (foundID = false) {
System.out.println("Account not found. Transaction failed. Deposit reimbursed");
this.balance += x;
return;
}
}
}
// Constructors
public eBanking(String name){
int firstDigit = (int)(Math.random() * 10);
int secondDigit = (int)(Math.random() * 10);
int thirdDigit = (int)(Math.random() * 10);
int forthDigit = (int)(Math.random() * 10);
accountID = this.toString();
PIN = Integer.toString(firstDigit) + secondDigit + thirdDigit + forthDigit; //Nuk e kuptova perse nese i jap Integer.toString te pares i merr te gjitha
balance = 0; //dhe nuk duhet ta perseris per the gjitha
accountName = name;
accounts[numberOfAccount] = this;
numberOfAccount++;
System.out.println("---------------------------------------------------------------------------------------");
System.out.println(accountName + ": Your balance is " + balance + ", your PIN is: " + PIN + " and your account number is: " + accountID);
}
public eBanking(String name, String pin, int x){
if (checkPIN(pin) == false) {
System.out.println("Incorrect PIN format!");
return;
}
accountID = this.toString();
accountName = name;
balance = x;
PIN = pin;
accounts[numberOfAccount] = this;
numberOfAccount++;
welcome();
}
}
import java.util.Scanner;
public abstract class BankAccount {
// Variable declaration
protected String PIN;
protected int balance;
public static int numberOfAccount = 0;
protected static int initialBalance; // E kam perdorur per te bere menune me dinamike sidomos per metoden transfer();
//Methods
//Balance
public int getBalance() {
return balance;
}
public void showBalance() {
System.out.println("The total balance of the account is " + balance);
}
public void withdraw(int x) {
initialBalance = balance;
if (balance == 0) {
System.out.println("The deduction has failed due to lack of balance!");
return;
}
if (balance < x) {
balance = 0;
System.out.println("The deduction of " + initialBalance + " from your balance is completed!");
} else {
balance -= x;
System.out.println("The deduction of " + x + " from your balance is completed!");
}
}
public void deposit(int x) {
balance += x;
System.out.println("You have made a deposit of " + x + " and your current balance is " + balance);
}
//PIN
public String getPIN() {
return PIN;
}
public void changePIN() {
Scanner input = new Scanner(System.in);
System.out.print("Please enter your previous PIN: ");
String tryPIN = input.nextLine();
if (tryPIN.equals(PIN)) {
System.out.print("Please enter your new PIN: ");
String newPIN = input.nextLine();
if (checkPIN(newPIN) == false) {
System.out.println("The PIN is not in the correct format!");
} else {
System.out.println("The PIN has been changed");
PIN = newPIN;
}
} else {
System.out.println("The PIN does not match!");
}
}
protected static boolean checkPIN(String str) {
boolean isValid;
if(str.length() != 4) {
isValid = false;
} else {
try {
int x = Integer.parseInt(str);
isValid = true;
} catch (NumberFormatException e) {
isValid = false;
}
}
return isValid;
}
//Kjo metode duhet per testim
public void getDetails() {
System.out.println(balance + " and PIN " + PIN);
}
}
I have updated the post showing how I fixed it and providing all my classes. Please do not mind the messy code as I am first trying it out with a switch and then will ditch that when the time comes and use GUI as soon as I learn how to use it. Also I know that the classes can be organized better but BankAccount and eBanking are 2 salvaged classes I used on a different exercise.
I think I have found a solution. I just remembered that when using FileWriter if a file does not exist it creates one automatically. So i have cancelled the method which creates a file whenever a new object is created and now whenever the program is closed the files are created if needed or overwritten if they already exist.
I have provided all the current code on my program and the fix I implemented on FileManagment class
The program works but you need to type in Upper case or Lower case depending on the word. As well, when you choose 2 or more standard/deluxe toppings, it displays only the last input of each one. Definitely waiting for help :D. Thank you!
public class Sundae {
private final double SALES_TAX = .08625;
private final double DELUXE_TOPPING = 1.25;
private String iceCreamFlavor;
private int numberOfScoops;
private double costForScoops;
private String standardToppingList;
private String freeSyrupChoice;
private String deluxeToppingList;
private double costOfDeluxeToppings;
private int counterD;
private double costOfSundae;
private double tax;
private double total;
public Sundae()
{
}
public String getIceCreamFlavor()
{
return iceCreamFlavor;
}
public int getNumberOfScoops()
{
return numberOfScoops;
}
public double getCostForScoops()
{
return costForScoops;
}
public String getStandardToppingList()
{
return standardToppingList;
}
public String getFreeSyrupChoice()
{
return freeSyrupChoice;
}
public String getDeluxeToppingList()
{
return deluxeToppingList;
}
public double getCostOfDeluxeToppings()
{
return costOfDeluxeToppings;
}
public int getCounterD()
{
return counterD;
}
public double getCostOfSundae()
{
return costOfSundae;
}
public void setIceCreamFlavor(String choice)
{
iceCreamFlavor = choice;
}
public void setNumberOfScoops(int numberScoops)
{
numberOfScoops = numberScoops;
}
public void setCostForScoops()
{
costForScoops = numberOfScoops + 1.79;
}
public void setCounterD(int numberD)
{
counterD = numberD;
}
public void setStandardToppingList(String standardTopping)
{
standardToppingList = standardTopping;
}
public void setFreeSyrupChoice(String syrup)
{
freeSyrupChoice = syrup;
}
public void setDeluxeToppingList(String deluxeTopping)
{
deluxeToppingList = deluxeTopping;
}
public void setDefault()
{
iceCreamFlavor = "Vanilla";
numberOfScoops = 2;
costForScoops = 1.79;
standardToppingList = "Whipped Cream, Hot Fudge, Multi-Colored Sprinkles, and a cherry.";
}
public void Print()
{
costForScoops = numberOfScoops * 1.79;
costOfDeluxeToppings = DELUXE_TOPPING * counterD;
costOfSundae = costForScoops + costOfDeluxeToppings;
tax = SALES_TAX * costOfSundae;
total = costOfSundae + tax;
System.out.println("Flavor: " + iceCreamFlavor + "\nNumber of scoops: " + numberOfScoops + "\nCost for scoops: " + costForScoops
+ "\nStandard toppings: " + standardToppingList + "\nSyrup:" + freeSyrupChoice + "\nDeluxe toppings: " + deluxeToppingList
+ "\nCost of deluxe toppings: " + costOfDeluxeToppings);
System.out.printf("Subtotal: $%.2f \nSale Tax: $%.2f \nTotal: $%.2f", costOfSundae, tax, total);
}
}
Driver Program
import java.util.Scanner;
public class SundaeDriver {
public static void main(String[]args) {
Sundae sundae = new Sundae();
int numberS;
int numberD;
Scanner input = new Scanner(System.in);
System.out.println("Which sundae flavor do you want? ");
sundae.setIceCreamFlavor(input.nextLine());
if ((sundae.getIceCreamFlavor().equalsIgnoreCase("Vanilla"))||
(sundae.getIceCreamFlavor().equalsIgnoreCase("French Vanilla"))||
(sundae.getIceCreamFlavor().equalsIgnoreCase("Peanut Butter"))||
(sundae.getIceCreamFlavor().equalsIgnoreCase("Chocolate"))||
(sundae.getIceCreamFlavor().equalsIgnoreCase("Chocolate Chip"))||
(sundae.getIceCreamFlavor().equalsIgnoreCase("Chocolate Chip Cookie"))||
(sundae.getIceCreamFlavor().equalsIgnoreCase("Cookie Dough"))||
(sundae.getIceCreamFlavor().equalsIgnoreCase("Ice Cream Cake"))||
(sundae.getIceCreamFlavor().equalsIgnoreCase("American Dream"))||
(sundae.getIceCreamFlavor().equalsIgnoreCase("Vanilla Chocolate Swirl"))||
(sundae.getIceCreamFlavor().equalsIgnoreCase("Strawberry"))||
(sundae.getIceCreamFlavor().equalsIgnoreCase("Mint Chocolate Chip"))||
(sundae.getIceCreamFlavor().equalsIgnoreCase("Oreo Cookies and Cream")))
{
}
else
{
sundae.setIceCreamFlavor("Vanilla");
}
System.out.println("How many scoops do you want?");
sundae.setNumberOfScoops(input.nextInt());
if ((sundae.getNumberOfScoops() == 1)||
(sundae.getNumberOfScoops() == 2)||
(sundae.getNumberOfScoops() == 3)||
(sundae.getNumberOfScoops() == 4)||
(sundae.getNumberOfScoops() == 5)||
(sundae.getNumberOfScoops() == 6))
{
}
else
{
sundae.setNumberOfScoops(2);
}
System.out.println("How many free toppings do you want?(free)");
numberS = input.nextInt();
input.nextLine();
for (int i = 0; i < numberS;i++)
{
System.out.println((i + 1) + " free toppings do you want?");
sundae.setStandardToppingList(input.nextLine());
if ((sundae.getStandardToppingList().equals("Whipped cream"))||
(sundae.getStandardToppingList().equals("Syrup"))||
(sundae.getStandardToppingList().equals("Multi colored sprinkles"))||
(sundae.getStandardToppingList().equals("Cherry")))
{
sundae.getStandardToppingList();
}
else
{
sundae.setStandardToppingList("Whipped cream, hot fudge, multi colored sprinkles and cherry");
}
}
System.out.println("Which syrup do you want?");
sundae.setFreeSyrupChoice(input.nextLine());
if ((sundae.getFreeSyrupChoice().equals("Hot fudge"))||
(sundae.getFreeSyrupChoice().equals("Chocolate"))||
(sundae.getFreeSyrupChoice().equals("Caramel")))
{
}
else
{
sundae.setFreeSyrupChoice("");
}
System.out.println("How many deluxe toppings do you want?");
numberD = input.nextInt();
sundae.setCounterD(numberD);
sundae.getCounterD();
input.nextLine();
for(int j = 0; j < numberD; j++)
{
System.out.println((j + 1) + " deluxe toppings do you want?");
sundae.setDeluxeToppingList(input.nextLine());
if((sundae.getDeluxeToppingList().equals("M&Ms"))||
(sundae.getDeluxeToppingList().equals("Crushed oreos"))||
(sundae.getDeluxeToppingList().equals("Reeses")||
(sundae.getDeluxeToppingList().equals("Chocolate chips"))||
(sundae.getDeluxeToppingList().equals("KitKats"))||
(sundae.getDeluxeToppingList().equals("Gummy Bears"))||
(sundae.getDeluxeToppingList().equals("Cookie Dough Bits"))||
(sundae.getDeluxeToppingList().equals("Marshmallows"))||
(sundae.getDeluxeToppingList().equals("Peanuts"))||
(sundae.getDeluxeToppingList().equals("Walnuts"))))
{
sundae.getDeluxeToppingList();
}
else
{
sundae.setDeluxeToppingList("");
}
}
sundae.Print();
input.close();
}
}
This looks like a perfect time to use enum(s). I'll provide an example for the first case. Ice cream flavors.
public enum IceCreamFlavors {
VANILLA, FRENCH_VANILLA, PEANUT_BUTTER, CHOCOLATE, CHOCOLATE_CHIP,
CHOCOLATE_CHIP_COOKIE, COOKIE_DOUGH, ICE_CREAM_CAKE, AMERICAN_DREAM,
VANILLA_CHOCOLATE_SWIRL, STRAWBERRY, MINT_CHOCOLATE_CHIP, OREOS_COOKIES_AND_CREAM;
public static IceCreamFlavors fromName(String name) {
for (IceCreamFlavors f : values()) {
if (f.name().replace('_', ' ').equalsIgnoreCase(name)) {
return f;
}
}
return IceCreamFlavors.VANILLA;
}
}
Then you can call it like
System.out.println("Which ice cream flavor do you want? ");
IceCreamFlavors flavor = IceCreamFlavors.fromName(input.nextLine());
And that way your logic for validation of the flavor it kept with-in the enum.
use:
private List<String> standardToppingList;
private List<String> deluxToppingList;
with Constructor containing:
standardToppingList = new Arraylist<>();
deluxToppingList = new Arraylist<>();
to add to the list, use:
standardToppingList.add(standardTopping);
deluxToppingList.add(deluxTopping);
and Display Using:
for(String s : deluxToppingList) {
System.out.println(s);
}
for(String s : standardToppingList) {
System.out.println(s);
}
I'm trying to write a bank account that asks the user if they want to see records, remove records, and other stuff. This is what I'm trying to produce
My program is nearly done the only problem I'm having is getting the output. I'm getting some weird error when i tried producing the output. When the output works. I'll put it inside a linked list.
public class Bank
{
public static void main(String args[]){
ArrayList<Customer> accounts = new ArrayList<Customer>();
Customer customer1 = new Customer(1, "Savings", "Dollars", 800);
Customer customer2 = new Customer(2, "Checking", "Euro", 1900);
Customer customer3 = new Customer(3, "Checking", "Pound", 8000);
accounts.add(customer1);
accounts.add(customer2);
accounts.add(customer3);
int customerID=4;
String choice;
int deposit;
int withdraw;
Scanner in = new Scanner(System.in);
Customer operation = new Customer();
boolean flag = true;
String accountType;
String currencyType;
int balance;
while(flag){
System.out.println("Select a choice:");
System.out.println("1. Existing customer");
System.out.println("2. New customer");
System.out.println("3. Quit");
String input = in.next();
//existing user
if(input.equals("1")){
System.out.println("Enter CustomerID: ");
customerID = in.nextInt();
System.out.println("Would you like to: ");
System.out.println("1. Deposit ");
System.out.println("2. Withdraw ");
System.out.println("3. Display account info ");
System.out.println("4. Check balance ");
choice = in.next();
if(choice.equals("1")){
System.out.println("How much would you like to deposit?");
deposit = in.nextInt();
operation.deposit(deposit);
}
else if (choice.equals("2")){
System.out.println("How much would you like to withdraw?");
withdraw = in.nextInt();
operation.withdraw(withdraw);
}
else if (choice.equals("3")){
operation.display(accounts.get(customerID));
}
else if (choice.equals("4"))
operation.balance(accounts.get(customerID));
else
System.out.println("Invalid");
}
//new user
else if(input.equals("2")){
//add new user to arraylist
int newID = customerID + 1;
System.out.println("Enter account type: ");
accountType = in.next();
System.out.println("Enter currency type: ");
currencyType = in.next();
System.out.println("Enter initial balance: ");
balance = in.nextInt();
System.out.println("Your customer ID will be: " + newID);
accounts.add(new Customer(newID, accountType, currencyType, balance));
}
else if(input.equals("3")){
System.out.println("Thanks for using this bank!");
flag = false;
}
else{
System.out.println("Invalid");
}
}
}
}
My second class:
public class Customer
{
String accountType, currencyType, info;
public int customerID, balance, amount;
Scanner input = new Scanner(System.in);
public Customer(int customerID, String accountType, String currencyType, int balance)
{
this.accountType = accountType;
this.currencyType = currencyType;
this.customerID = customerID;
this.balance = balance;
this.amount = amount;
}
public Customer() {
// TODO Auto-generated constructor stub
}
public int deposit(int amount){
amount = input.nextInt();
if (amount >= 500) {
System.out.println("Invalid");
}
else{
balance = balance + amount;
}
return balance;
}
public int withdraw(int amount){
if (balance < amount) {
System.out.println("Invalid amount.");
}
else if (amount >= 500) {
System.out.println("Invalid");
}
else {
balance = balance - amount;
}
return balance;
}
public void display(ArrayList<Customer> accounts)
{
System.out.println("CustomerID:" + accounts.customerID);
System.out.println("Account Type:" + accounts.accountType);
System.out.println("Currency Type: " + accounts.currencyType);
System.out.println("Balance:" + accounts.balance);
}
public void balance(ArrayList<Customer> accounts) {
System.out.println("Balance:" + accounts.balance);
}
}
java.util.ArrayList won't have properties or methods such as customerID, accountType, currencyType and balance.
I guess your methods display() and balance() shoudn't take any arguments and should use the properties of the instance to print.
public void display()
{
System.out.println("CustomerID:" + customerID);
System.out.println("Account Type:" + accountType);
System.out.println("Currency Type: " + currencyType);
System.out.println("Balance:" + balance);
}
public void balance() {
System.out.println("Balance:" + balance);
}
Then, these lines
operation.display(accounts.get(customerID));
operation.balance(accounts.get(customerID));
should be
accounts.get(customerID).display();
accounts.get(customerID).balance();
There seems many more things to be corrected -- for example, usage of withdraw().
I'm involved in a group assignment where we are supposed to create a bank program. This is our first time programming in java. We are stuck and we are having trouble figuring out how to connect our customer and account classes. They both consist of ArrayLists and we want the customer arraylists to contain the accounts. So that if we delete a customer, the accounts that belong to that customer will also be deleted. Can anyone give us a push in the right direction?
This is our main class which contains the bank menu:
package bank6;
import java.util.Scanner;
import java.util.HashMap;
import java.util.Map;
public class Bankmenu {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Customer client = new Customer();
Account bank = new Account();
Account accs = new Account();
Customer cust1, cust2, cust3;
cust1 = new Customer("8905060000", "Henrik");
cust2 = new Customer("8910210000", "Emelie");
cust3 = new Customer("8611040000", "Fredrik");
bank.addNewAccount(cust1);
bank.addNewAccount(cust2);
bank.addNewAccount(cust3);
client.addCustomerAr(cust1);
client.addCustomerAr(cust2);
client.addCustomerAr(cust3);
int ChoiceOne = 0;
int CustChoice;
int currentCustomer;
int currentAccount;
int amountC;
int amountD;
int editCust;
String personNummer = null;
String Pnr = "0";
int AdminChoice;
/*prompts the user to set ChoiceOne equal to 1 or 2. Hasnextint checks
if the input is an int. else asks for new input. */
while (ChoiceOne != 1 && ChoiceOne != 2) {
System.out.println("Press 1 to login as customer or 2 to login as admin ");
if (input.hasNextInt()) {
ChoiceOne = input.nextInt();
System.out.println();
} else {
System.out.println("You must enter number 1 or number 2");
input.next();
}//ends else
}//ends while
/*
If the user chooses 1 in the previous question, the user will be sent to
the interface for the customer. User is then asked to enter his social
security number and this number will be checked using the Luhn algoritm. Since
the scanner input is already used we added a new Scanner calleds nexLine
to deal with custPnr as a string.
(http://stackoverflow.com/questions/5032356/using-scanner-nextline)
*/
if (ChoiceOne == 1) {
//boolean quit=false;
while ("0".equals(Pnr)) {
// System.out.println("Welcome customer. Please login by using your birthdate (yymmddnnnn) ");
// Scanner nextLine = new Scanner(System.in);
// Pnr = nextLine.nextLine();
//Luhn.checkLogin(Pnr);
//Här måste en kontroll med Luhn algoritmen göras.
// getUserBirthdate();
boolean CorrectBirthDate = false;
while (CorrectBirthDate == false) {
System.out.println("Please enter your birthdate");
Scanner inception = new Scanner(System.in);
personNummer = inception.next();
CorrectBirthDate = Luhn.checkLogin(personNummer);
if (CorrectBirthDate == false) {
System.out.println("Incorrect birthdate. You will be prompted to type it again");
}
}
break;
/* }
Sets "quit" to false and executes quit=true if customer chooses case 0
*/
}
boolean quit = false;
do {
// boolean quit = false;
//System.out.println();
System.out.println("Logged on as " + personNummer);
System.out.println("1. deposit money");
System.out.println("2. Withdraw money");
System.out.println("3. Check balance");
System.out.print("Your choice, 0 to quit: ");
CustChoice = input.nextInt();
switch (CustChoice) {
case 1: //Deposit money
System.out.println(bank.getAccountNumbersFor(personNummer));
System.out.println("Enter account number:");
currentAccount = input.nextInt();
System.out.println("Enter amount to deposit:");
amountC = input.nextInt();
System.out.println(bank.creditAccount(currentAccount, amountC));
System.out.println(bank.getAccountNumbersFor("Henrik"));
break;
case 2://Withdraw money
// System.out.println(bank.getAccNosFor(custPnr));
bank.getAccountNo();
System.out.println("Enter account number:");
currentAccount = input.nextInt();
System.out.println("Enter amount to withdraw:");
amountD = input.nextInt();
System.out.println(bank.debitAccount(currentAccount, amountD));
System.out.println(bank.getAccountNumbersFor("Henrik"));
break;
case 3://Check ballance and accounts
System.out.println(bank.getAccountNumbersFor("Henrik"));
break;
case 0:
quit = true;
break;
default:
System.out.println("Wrong choice.");
break;
}
System.out.println();
} while (!quit);
System.out.println("Bye!");
}//ends if
else if (ChoiceOne == 2) {
while ("0".equals(Pnr)) {
boolean CorrectBirthDate = false;
while (CorrectBirthDate == false) {
System.out.println("Please enter your birthdate");
Scanner inception = new Scanner(System.in);
personNummer = inception.next();
CorrectBirthDate = Luhn.checkLogin(personNummer);
if (CorrectBirthDate == false) {
System.out.println("Incorrect birthdate. You will be prompted to type it again");
}
}
break;
}
//AdminpNr = input.nextInt();
//Här måste en kontroll av AdminpNr göras med hjälp av Luhn.
boolean quit = false;
do {
System.out.println("1. Add customer");
System.out.println("2. Add account");
System.out.println("3. List customer");
System.out.println("4. List accounts");
System.out.println("5. Remove customer");
System.out.println("6. Remove account");
System.out.print("Your choice, 0 to quit: ");
AdminChoice = input.nextInt();
switch (AdminChoice) {
case 1://add customer
int i = 0;
do {
System.out.println("Skriv in nytt personnummer:");
Scanner scan = new Scanner(System.in);
Map<String, Customer> testCustomers = new HashMap<String, Customer>();
String name = scan.nextLine();
//System.out.println("Att arbeta på bank ska vara jobbigt, skriv in det igen:");
//String pnummer = scan.nextLine();
String pnummer = name;
System.out.println("Skriv in namn:");
String kundnamn = scan.nextLine();
Customer obj = new Customer(pnummer, kundnamn);
testCustomers.put(name, obj);
client.addCustomerAr(obj);
i++;
} while (i < 2);
break;
case 2://add account
int i2 = 0;
do {
System.out.println("Skriv in nytt personnummer:");
Scanner scan = new Scanner(System.in);
Map<Long, Account> testAccs = new HashMap<Long, Account>();
Long name = scan.nextLong();
//System.out.println("Skriv in personnummer igen:");
Long own = name;
long bal = 0;
Account obt = new Account(own, bal);
testAccs.put(name, obt);
accs.addAccAr(obt);
i2++;
} while (i2 < 2);
break;
case 3:// List customer and accounts
for (String info : client.getAllClients()) {
System.out.println(info);
}
break;
case 4:
for (Long infoAcc : accs.getAllAccounts()) {
System.out.println(infoAcc);
}
break;
case 5:
// ta bort kund
break;
case 6:
// ta bort konto
break;
case 0:
quit = true;
break;
default:
System.out.println("Wrong choice.");
break;
}
System.out.println();
} while (!quit);
System.out.println("Bye!");
}//ends else if
}//ends main
/* private static void getUserBirthdate() {
boolean CorrectBirthDate = false;
while (CorrectBirthDate == false) {
System.out.println("Please enter your birthdate");
Scanner inception = new Scanner (System.in);
String personNummer = inception.next();
CorrectBirthDate = Luhn.checkLogin(personNummer);
if (CorrectBirthDate == false) {
System.out.println("Incorrect birthdate. You will be prompted to type it again");
}
}
}
*/
}//ends class
This is our Account class;
package bank6;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
public class Account {
private ArrayList accounts;
private Object lastAcc;
public String customerSocial;
private Integer balance;
private Integer accountNumber;
private Customer owner;
private Account Customer6; // Association customer/account.
private ArrayList<Account> myAccounts = new ArrayList<Account>();
public Integer deposit;
public Integer withdraw;
static Integer accountNo = 1010;
private Long persnr;
private long balans = 0;
/*Constructor.. A account cannot exist unless it is owned by a customer*/
public Account(Customer owner, Integer balance) {
this.owner = owner;
this.balance = balance;
accountNumber = accountNo++;
}
public Account() {
accounts = new ArrayList();
}
public Account(Long persnr, long balans) {
this.persnr = persnr;
this.balans = balans;
accountNumber = accountNo++;
}
public Integer getAccountNo() {
return accountNumber;
}
public String getOwner() {
return owner.getName();
}
public Customer getOwn() {
return owner;
}
public Integer getBalance() {
return balance;
}
//credits the account with an amount of money and returns a string
public String credit(Integer anAmount) {
balance += anAmount;
// return "Account number " + accountNumber + " Has been credited with "+anAmount + " kr.";
return " " + anAmount + " kr has been deposited to " + accountNumber + "\n";
}
public boolean canDebit(Integer anAmount) {
return anAmount <= balance;
}
public String debit(Integer anAmount) {
if (this.canDebit(anAmount)) {
balance -= anAmount;
return " " + anAmount + " kr has been withdrawn from " + accountNumber + "\n";
} else {
return "Account number" + accountNo + "has insufficient funds to debit"
+ anAmount;
}
}
public void addNewAccount(Customer customer) {
accounts.add(new Account(customer, 0));
lastAcc = accounts.get(accounts.size() - 1);
System.out.println("*** New account created. ***" //+ lastAcc
+ "\n");
}
public String removeAccount(int accountNumber) {
boolean found = false;
String results = "";
ListIterator iter = accounts.listIterator();
while (iter.hasNext() && found) {
Account account = (Account) iter.next();
if (account.getAccountNo() == accountNumber) {
found = true; //there is a match stop the loop
if (account.getBalance() == 0) {
iter.remove();//remove this account object
results = "Account number " + accountNumber + " has been removed";
} else {
results = "Account number " + accountNumber + " cannot be removed"
+ "as it has a balance of: " + account.getBalance();
}
}//ends if there is a match
}// end while loop
if (!found) {
results = "No such account";
}
return results;
}
public String creditAccount(int accountNumber, Integer anAmount) {
boolean found = false;
String results = "";
ListIterator iter = accounts.listIterator();
while (iter.hasNext() && !found) {
Account account = (Account) iter.next();
if (account.getAccountNo() == accountNumber) {
results = account.credit(anAmount);
found = true;//stop the loop
}
}
if (!found) {
results = "No such customer";
}
return results;
}
public String debitAccount(int accountNumber, Integer anAmount) {
boolean found = false;
String results = "";
ListIterator iter = accounts.listIterator();
while (iter.hasNext() && !found) {
Account account = (Account) iter.next();
if (account.getAccountNo() == accountNumber) {
results = account.debit(anAmount);
found = true;
}
}
if (!found) {
results = "No such Customer";
}
return results;
}
public String getAccountNumbersFor(String CustomerName) {
String details = CustomerName + " has the followinng accounts: "
+ "\n\n";
Iterator iter = accounts.iterator();
//visit all of the accounts in the ArrayList
while (iter.hasNext()) {
Account account = (Account) iter.next();
if (account.getOwner().equals(CustomerName)) {
details += " Account number " + account.getAccountNo()
+ " Balance " + account.getBalance() + "kr \n";
}//ends if
}//ends while
return details;
}
public String bankAccounts() {
String details = "ALL BANK ACCOUNTS" + "\n"
+ "-----------------" + '\n';
if (accounts.size() == 0) {
details += "There are no bank accounts";
} else {
Iterator iter = accounts.iterator();
while (iter.hasNext()) {
details += iter.next().toString() + '\n';
}
}
return details;
}
#Override
public String toString() {
return "Account " + accountNumber + ": " + owner
+ "\nBalance: " + balance + " kr.\n";
}
public Boolean authenticateUser(String login, String ssn) {
if (Luhn.checkLogin(ssn)) {
System.out.println("User authenticated");
return true;
} else {
System.out.println("Authentication refused");
return false;
}
}
public void addAccAr(Account myAccount) {
myAccounts.add(myAccount);
}
public Long getBalanceToLong() {
long balTemp = balans;
return balTemp;
}
public Long getPnTorLong() {
return persnr;
}
public Long getAccNoLong() {
long accTemp = accountNumber;
return accTemp;
}
public ArrayList<Long> getAllAccounts() {
ArrayList<Long> allAccounts = new ArrayList<>();
System.out.println("ALL ACCOUNTS\n-----------");
for (Account myAccount : myAccounts) {
allAccounts.add(myAccount.getAccNoLong());
allAccounts.add(myAccount.getPnTorLong());
allAccounts.add(myAccount.getBalanceToLong());
}
return allAccounts;
}
/*
public ArrayList<String> getMyAccounts() {
ArrayList<String> ownAccounts = new ArrayList<>();
System.out.println("MY ACCOUNTS\n-----------");
for (Account myAccount : myAccounts) {
ownAccounts.add(myAccount.getAccNoStr());
ownAccounts.add(myAccount.getBalanceToStr());
}
return ownAccounts;
}*/
}
This is our Customer class
package bank6;
import java.util.ArrayList;
public class Customer {
int custCounter;
//attribut
private Long socialNo;
private String name;
private ArrayList customers;
public Integer customerNumber;
static Integer custNo = 1;
private ArrayList<Customer> clients = new ArrayList<Customer>();
//konstruktor
public Customer(String socialStr, String name) {
Long socialTemp = new Long(socialStr);
this.name = name;
this.socialNo = socialTemp;
customerNumber = custNo++;
}//ends konstruktor customer6
public Customer() {
customers = new ArrayList();
}
/* Set methods*/
public void setName(String name) {
this.name = name;
}
public void setsocialNo(Long socialNo) {
this.socialNo = socialNo;
}
/* get methods */
public String getName() {
return name;
}
public String getSocialNoStr() {
String socialTemp = Long.toString(socialNo);
return socialTemp;
}
public Long getSocialNo() {
return socialNo;
}
/*toString() method*/
#Override
public String toString() {
return "\n" + "Owner: " + name + " (" + socialNo + ")";
}
public void addAccCustAr() {
}
public void addCustomerAr(Customer client) {
clients.add(client);
}
public ArrayList<String> getAllClients() {
ArrayList<String> allClients = new ArrayList<>();
System.out.println("ALL CLIENTS\n-----------");
for (Customer client : clients) {
allClients.add(client.getName());
allClients.add(client.getSocialNoStr() + "\n");
}
return allClients;
//add account
//public void addAccount(account6 account){
// accounts.add(account);
//}// ends adds account
//remove account
//public void removeAccount (account6 account) {
// accounts.remove(account);
//}//ends remove account
}
}//ends public class
This is our Luhn class
package bank6;
public class Luhn {
public static boolean checkLogin(String pnr) {
if (pnr.length() != 10) {
System.out.println("");
return false;
} else {
int length = pnr.length();
int sum = 0;
int pos = length - 1;
for (int i = 1; i <= length; i++, pos--) {
char tmp = pnr.charAt(pos);
int num = Integer.parseInt(String.valueOf(tmp));
int produkt;
if (i % 2 != 0) {
produkt = num * 1;
} else {
produkt = num * 2;
}
if (produkt > 9) {
produkt -= 9;
}
sum += produkt;
}
boolean korrekt = (sum % 10) == 0;
if (korrekt) {
System.out.println("Correct");
return true;
} else {
System.out.println("Invalid");
return false;
}
}
}
}
Your Account class already has a Customer field -- good.
You should give Customer an ArrayList<Account> accounts field.
And also give Customer addAccount(Account acct) and removeAccount(Account acct) methods.
Why does Customer have an ArrayList<Customer> field? That makes little sense. Should a Customer hold a list of other Customers? Why? For what purpose?
Why does Account have private ArrayList<Account> myAccounts = new ArrayList<Account>();? That also makes little sense. Should an Account hold a bunch of other Accounts? Again, for what purpose?
The Account class should logically represent one and only one Account.
Same for the Customer class -- it should logically represent only one Customer.
If you think through things logically, they usually come together, and each component of your code should make sense. If it doesn't, question why it is there.
So this code is broken:
Account bank = new Account();
//....
bank.addNewAccount(cust1);
bank.addNewAccount(cust2);
bank.addNewAccount(cust3);
Since you're adding a bunch of Customer's to an Account object. It looks like you should have another class, a Bank class, one that can hold an ArrayList<Customer>. Wouldn't this make sense?
Im writing a simple program to illustrate classes and inheritance in java. The program is Bank that has 2 classes Account and Operation where Operation extends Account. Now in main I declared the values in Account and then I started calling the operations from Operation class. now whenever Operation calls the values in Account it return 0 for int and null for string though I added value to it.
Here is the Account:
public class Account {
private String Name;
private int ID;
private double Money;
Account()
{
}
Account (String n, int i, double m)
{
Name = n;
ID = i;
Money = m;
}
public void setMoney(double m)
{
Money = m;
}
public double getMoney()
{
return Money;
}
public int getID()
{
return ID;
}
public String getName()
{
return Name;
}
public void Check()
{
System.out.println("Your Name is: " + Name + " Your ID is: " + String.valueOf(ID) + " Your Balance is: " + String.valueOf(Money));
}
}
Here is the Operation class:
import java.util.Date;
public class Operation extends Account{
private Date TransactionDate;
public void Withdraw(double amount)
{
double Money = getMoney();
if (amount > Money)
System.out.println("The amount is insufficient");
else
{
Money = Money - amount;
TransactionDate = new Date();
setMoney(Money);
System.out.println("The available money is " + String.valueOf(Money) + " at " + String.valueOf(TransactionDate));
}
}
public void Deposit(double amount)
{
double Money = getMoney();
if (amount < 0)
System.out.println("You cant add minus");
else
{
Money = Money + amount;
TransactionDate = new Date();
setMoney(Money);
System.out.println("Your credits are: " + String.valueOf(Money) + " at " + String.valueOf(TransactionDate));
}
}
public void Check()
{
String Name = getName();
int ID = getID();
double Money = getMoney();
System.out.println("Your Name is: " + Name + " Your ID is: " + String.valueOf(ID) + " Your Balance is: " + String.valueOf(Money));
}
}
Here is the main:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
/**
* #param args
* #throws IOException
* #throws NumberFormatException
*/
public static void main(String[] args) throws NumberFormatException,
IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter your ID");
int ID = Integer.parseInt(br.readLine());
System.out.println("Enter your Name");
String Name = br.readLine();
System.out.println("Enter your Money");
double Money = Double.parseDouble(br.readLine());
Account a = new Account(Name, ID, Money);
a.Check();
Operation o = new Operation();
while (true) {
System.out.println("\n-----------------------------------");
System.out
.println("Enter 1 to withdraw, 2 to Deposit, 3 to Check, 4 to exit ");
int operation = Integer.parseInt(br.readLine());
switch (operation) {
case 1:
System.out.println("enter the amount");
double withdrawMoney = Double.parseDouble(br.readLine());
o.Withdraw(withdrawMoney);
break;
case 2:
System.out.println("enter the amount");
double Depositmoney = Double.parseDouble(br.readLine());
o.Deposit(Depositmoney);
break;
case 3:
o.Check();
break;
case 4:
break;
default:
System.out.println("enter between 1 and 4 only");
}
if (operation == 4)
break;
}
}
}
I really don't know why Operation cant read the values I added to Account since Operation extends Account can you please explain it to me the reason and how to fix it.
Thanks in advance.
You have two separate objects -- one an Account, and one an Operation.
An instance of your Operation class has a name, ID and money - but they're not the same name, ID and money as other instances of Account or Operation.
One way to fix it would be to add a constructor to Operation:
class Operation {
Operation(String n, int i, double m) {
super( n, i, m );
}
...
}