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 );
}
...
}
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
I'm trying to create an account class in java. My main issue is not with the class itself but with the output. In short I'm using an array to store bank account information and then checking for an id after to deposit/withdraw a certain amount. My issue is that when I try typing in an invalid value for the id (this is for the checking/searching portion) I should get an output of "account not found" however, for some reason I end up getting five outputs of the same line "account not found" (probably has to do something with the array size but I can't quite figure it out). Is there a way to get it to only print out the line once?
tl;dr: When typing an invalid Id I should only get one line of "account not found", getting multiple instead
import java.util.Scanner;
public class AccountDriver
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
int id =0;
double balance = 0;
double interest = 0;
Account[] accounts = new Account[5];
//this part fills in the array by asking the user information about each account
System.out.println("Enter the annual interest rate ");
interest = kb.nextDouble();
for (int i = 0; i < 5; i++)
{
System.out.println("Enter the account number: ");
id = kb.nextInt();
System.out.println("Enter the initial amount to deposit: ");
balance = kb.nextDouble();
Account a = new Account(id,balance,interest);
accounts[i] = a;
}
boolean repeat = true;
boolean found = false;
while(repeat)
{
System.out.println("\n\n*******************************");
System.out.println("Welcome to the BANK OF AMERICA");
System.out.println("\n\n*******************************");
System.out.println("Enter the account number to deposit, withdraw money :");
id = kb.nextInt();
int i = 0;
while (!found && i < 5)
{
if(id == accounts[i].getId())
{
System.out.println("Here is the account information currently:");
System.out.println(accounts[i]);
System.out.println("*******************");
System.out.println("Enter the amount of deposit: ");
double depositAmount = kb.nextDouble();
accounts[i].deposit(depositAmount);
System.out.println("Enter the amount to withdraw: ");
double withdrawAmount = kb.nextDouble();
if(!accounts[i].withdraw(withdrawAmount))
{
System.out.println("*******Not enough money in your account*********");
}
else
{
System.out.println("Here is the account information after your transaction:");
System.out.println(accounts[i]);
}
}
**//confused about this part**
else
{
System.out.println("Account not found");
}
i++;
}
//this asks the user if they have any other accounts to continue running the program
System.out.println("\nDo you have any other account?");
String answer = kb.next();
if(answer.equalsIgnoreCase("no"))
{
repeat = false;
}
}
}
}
Here's the class if anyone needs it
public class Account{
//These are instance variables
private static double annualInterestRate;
private int id;
private double balance;
//This creates an object from the date class in java
private java.util.Date dateCreated;
//This no argument constructor creates a default account
public Account()
{
dateCreated = new java.util.Date();
id = 0;
balance = 0;
annualInterestRate = 0;
}
//This constructor creates an account with
public Account(int newId, double newBalance, double newAnnualInterestRate)
{
//initialize the instance variables to the given values
dateCreated = new java.util.Date();
id = newId;
balance = newBalance;
annualInterestRate = newAnnualInterestRate;
}
//accessors (get)fill in the following methods
public int getId()
{
return id;
}
public double getBalance()
{
return balance;
}
public static double getAnnualInterestRate()
{
return annualInterestRate;
}
//mutators (get)
public void setId(int newId)
{
if (newId > 0)
{
id = newId;
}
}
public void setBalance(double newBalance)
{
if(newBalance >0)
{
newBalance = balance;
}
}
public static void setAnnualInterestRate(double newAnnualInterestRate)
{
if(newAnnualInterestRate > 0)
{
newAnnualInterestRate = annualInterestRate;
}
}
public double getMonthlyInterest()
{
double monthlyInterest = (balance * annualInterestRate/100 / 12);
return monthlyInterest;
}
public java.util.Date getDateCreated()
{
return dateCreated;
}
//this boolean method checks to see if the user has enough money to withdraw
public boolean withdraw(double amount)
{
if(amount > balance)
{
return false;
}
else
{
balance = balance - amount;
return true;
}
}
//this method returns the balance after the user enters an amount to deposit
public double deposit(double amount)
{
balance = balance + amount;
return balance;
}
//this method compares two accounts
public boolean equals(Account a)
{
return this.id == a.id;
}
//this method outputs the account information for each account
public String toString()
{
String s = "";
s = s + "ID: " + id;
s = s + String.format("\nBalance: %.2f", balance);
s = s + "\nAnnual interest rate: " + annualInterestRate;
double value = getMonthlyInterest();
s = s + String.format( "\nmonthly interest: %.2f", value);
s = s + "\nDate account created: " + dateCreated;
return s;
}
}
Put a Break after your System.out.println();
else{
System.out.println("Account not found");
//this will break your loop;
break;
}
or set your found to true
else{
System.out.println("Account not found");
//this will stop your inner while loop;
found = true;
}
Updated
i found out a lot of lapses on your code.
fix #1 : put your boolean found = false; inside you outer loop while(repeat) because you are going to change the value of that boolean variable later on inside your inner while loop. move your boolean found = false; after this declaration int i = 0;
fix #2 : after your transaction ends put a found = true; after your System.out.println(accounts[i]);
reason : this is to stop your inner while loop.
fix #3 : on your else condition put a if condition that will verify if there are no more next account. before terminating your inner loop.
else{
// i == 4 will return true after the loop reached the last account.
if(i == 4){
System.out.println("Account not found");
// this is to stop the inner loop if no account found .
found = true;
}
}
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I am almost done with an assignment. I am creating a Bank program, and I have almost everything done. The part that I am stuck on is the transactions part. I have to create a function public String getTransactionInfo(int n) which returns the last n transactions of a bank account. I cannot seem to figure this part out. i have a variable private int numOfTransactions and I tried incorporating that into the function, but it didn't work. this is what I tried.
public String gettransactionInfo(int n)
{
numOfTransactions = n;
return n;
}
that did not work. cannot figure out how to return this is a string. any ideas?
import java.util.Scanner;
public class BankApp {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
Bank myBank = new Bank();
int user_choice = 2;
do {
//display menu to user
//ask user for his choice and validate it (make sure it is between 1 and 6)
System.out.println();
System.out.println("1) Open a new bank account");
System.out.println("2) Deposit to a bank account");
System.out.println("3) Withdraw to bank account");
System.out.println("4) Print short account information");
System.out.println("5) Print the detailed account information including last transactions");
System.out.println("6) Quit");
System.out.println();
System.out.print("Enter choice [1-6]: ");
user_choice = s.nextInt();
switch (user_choice) {
case 1: System.out.println("Enter a customer name");
String cn = s.next();
System.out.println("Enter a opening balance");
double d = s.nextDouble();
System.out.println("Account was created and it has the following number: " + myBank.openNewAccount(cn, d));
break;
case 2: System.out.println("Enter a account number");
int an = s.nextInt();
System.out.println("Enter a deposit amount");
double da = s.nextDouble();
myBank.depositTo(an, da);
break;
case 3: System.out.println("Enter a account number");
int acn = s.nextInt();
System.out.println("Enter a withdraw amount");
double wa = s.nextDouble();
myBank.withdrawFrom(acn, wa);
break;
case 4: System.out.println("Enter a account number");
int anum = s.nextInt();
myBank.printAccountInfo(anum);
break;
//case 5: ... break;
}
}
while (user_choice != '6');
}
static class Bank {
private BankAccount[] accounts; // all the bank accounts at this bank
private int numOfAccounts; // the number of bank accounts at this bank
// Constructor: A new Bank object initially doesn’t contain any accounts.
public Bank() {
accounts = new BankAccount[100];
numOfAccounts = 0;
}
// Creates a new bank account using the customer name and the opening balance given as parameters
// and returns the account number of this new account. It also adds this account into the account list
// of the Bank calling object.
public int openNewAccount(String customerName, double openingBalance) {
BankAccount b = new BankAccount(customerName, openingBalance);
accounts[numOfAccounts] = b;
numOfAccounts++;
return b.getAccountNum();
}
// Withdraws the given amount from the account whose account number is given. If the account is
// not available at the bank, it should print a message.
public void withdrawFrom(int accountNum, double amount) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
accounts[i].withdraw(amount);
System.out.println("Amount withdrawn successfully");
return;
}
}
System.out.println("Account number not found.");
}
// Deposits the given amount to the account whose account number is given. If the account is not
// available at the bank, it should print a message.
public void depositTo(int accountNum, double amount) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
accounts[i].deposit(amount);
System.out.println("Amount deposited successfully");
return;
}
}
System.out.println("Account number not found.");
}
// Prints the account number, the customer name and the balance of the bank account whose
// account number is given. If the account is not available at the bank, it should print a message.
public void printAccountInfo(int accountNum) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
System.out.println(accounts[i].getAccountInfo());
return;
}
}
System.out.println("Account number not found.");
}
// Prints the account number, the customer number and the balance of the bank account whose
// account number is given, together with last n transactions on that account. If the account is not
// available at the bank, it should print a message.
public void printAccountInfo(int accountNum, int n) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
System.out.println(accounts[i].getAccountInfo());
System.out.println(accounts[i].getTransactionInfo(n));
return;
}
}
System.out.println("Account number not found.");
}
}
static class BankAccount{
private int accountNum;
private String customerName;
private double balance;
private double[] transactions;
private int numOfTransactions;
private static int noOfAccounts=0;
public String getAccountInfo(){
return "Account number: " + accountNum + "\nCustomer Name: " + customerName + "\nBalance:" + balance +"\n";
}
public String getTransactionInfo(int n)
{
numOfTransactions = n;
return n;
}
public BankAccount(String abc, double xyz){
customerName = abc;
balance = xyz;
noOfAccounts ++;
accountNum = noOfAccounts;
transactions = new double[100];
transactions[0] = balance;
numOfTransactions = 1;
}
public int getAccountNum(){
return accountNum;
}
public void deposit(double amount){
if (amount<=0) {
System.out.println("Amount to be deposited should be positive");
} else {
balance = balance + amount;
transactions[numOfTransactions] = amount;
numOfTransactions++;
}
}
public void withdraw(double amount)
{
if (amount<=0){
System.out.println("Amount to be withdrawn should be positive");
}
else
{
if (balance < amount) {
System.out.println("Insufficient balance");
} else {
balance = balance - amount;
transactions[numOfTransactions] = amount;
numOfTransactions++;
}
}
}
}//end of class
}
I think the correct solution to your problem will be something like this:
public String gettransactionInfo(int n)
{
//Traverse the "transactions" array in *reverse* order
//In For loop start with transactions.length, and decrement by 1 "n" times
// Append the transaction amount to a String
// Return the string.
}
public String gettransactionInfo(int n)
{
numOfTransactions = n;
return n;
}
Hehe! What are you exactly trying to do here? :) ... You messed up the rvalue and lvalue, but that's not related to the answer.
The key is to have a String Array in the class. Every time a transaction happens append the transaction details to the array..... Then gettransactionInfo should print the last n details in the string...
e.g.
transInfo[0] = "A deposited 30K"
transInfo[1] = "B withdrew 20K"
transInfo[2] = "C deposited 5k"
Last 1 transaction displays the last entry in the string "C deposited 5k"
If you want to return the number of transactions as a String, as opposed to the integer (which you have it stored as), then you want to convert the integer to a String.
In Java, you would do so via:
Integer.toString(numOfTransactions)
Side note: Out of curiosity, in your program, why are you doing this?
public String gettransactionInfo(int n)
{
numOfTransactions = n;
return n;
}
That is inefficient and wrong since you are setting the numberOfTransactions to the n value. That functionality, by convention is put in a setter method, as opposed to a getter method - which is what your implementation is supposed to do.
Ideally, it should be:
public String gettransactionInfo()
{
return Integer.toString(numOfTransactions);
}
EDIT:
As per the comments, the correct thing to do would be to return an index from the transactions array, corresponding to index n.
Where, in this case the transactions array should be a String array.
EDIT 2:
In the case where you use a separate string array, you would update it (depending on the transaction) as follows:
import java.util.Scanner;
public class BankApp {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
Bank myBank = new Bank();
int user_choice = 2;
do {
//display menu to user
//ask user for his choice and validate it (make sure it is between 1 and 6)
System.out.println();
System.out.println("1) Open a new bank account");
System.out.println("2) Deposit to a bank account");
System.out.println("3) Withdraw to bank account");
System.out.println("4) Print short account information");
System.out.println("5) Print the detailed account information including last transactions");
System.out.println("6) Quit");
System.out.println();
System.out.print("Enter choice [1-6]: ");
user_choice = s.nextInt();
switch (user_choice) {
case 1: System.out.println("Enter a customer name");
String cn = s.next();
System.out.println("Enter a opening balance");
double d = s.nextDouble();
System.out.println("Account was created and it has the following number: " + myBank.openNewAccount(cn, d));
break;
case 2: System.out.println("Enter a account number");
int an = s.nextInt();
System.out.println("Enter a deposit amount");
double da = s.nextDouble();
myBank.depositTo(an, da);
break;
case 3: System.out.println("Enter a account number");
int acn = s.nextInt();
System.out.println("Enter a withdraw amount");
double wa = s.nextDouble();
myBank.withdrawFrom(acn, wa);
break;
case 4: System.out.println("Enter a account number");
int anum = s.nextInt();
myBank.printAccountInfo(anum);
break;
case 5: System.out.println("Enter a account number");
anum = s.nextInt();
myBank.printTransactionInfo(anum);
break;
default: System.out.println("Invalid option. Please try again.");
}
}
while (user_choice != '6');
}
static class Bank {
private BankAccount[] accounts; // all the bank accounts at this bank
private int numOfAccounts; // the number of bank accounts at this bank
//Constructor: A new Bank object initially doesn’t contain any accounts.
public Bank() {
accounts = new BankAccount[100];
numOfAccounts = 0;
}
// Creates a new bank account using the customer name and the opening balance given as parameters
// and returns the account number of this new account. It also adds this account into the account list
// of the Bank calling object.
public int openNewAccount(String customerName, double openingBalance) {
BankAccount b = new BankAccount(customerName, openingBalance);
accounts[numOfAccounts] = b;
numOfAccounts++;
return b.getAccountNum();
}
// Withdraws the given amount from the account whose account number is given. If the account is
// not available at the bank, it should print a message.
public void withdrawFrom(int accountNum, double amount) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
accounts[i].withdraw(amount);
System.out.println("Amount withdrawn successfully");
return;
}
}
System.out.println("Account number not found.");
}
// Deposits the given amount to the account whose account number is given. If the account is not
// available at the bank, it should print a message.
public void depositTo(int accountNum, double amount) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
accounts[i].deposit(amount);
System.out.println("Amount deposited successfully");
return;
}
}
System.out.println("Account number not found.");
}
// Prints the account number, the customer name and the balance of the bank account whose
// account number is given. If the account is not available at the bank, it should print a message.
public void printAccountInfo(int accountNum) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
System.out.println(accounts[i].getAccountInfo());
return;
}
}
System.out.println("Account number not found.");
}
public void printTransactionInfo(int accountNum) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
System.out.println(accounts[i].getAccountInfo());
System.out.println("Last transaction: " + accounts[i].getTransactionInfo(accounts[i].getNumberOfTransactions()-1));
return;
}
}
System.out.println("Account number not found.");
}
// Prints the account number, the customer number and the balance of the bank account whose
// account number is given, together with last n transactions on that account. If the account is not
// available at the bank, it should print a message.
public void printAccountInfo(int accountNum, int n) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
System.out.println(accounts[i].getAccountInfo());
System.out.println(accounts[i].getTransactionInfo(n));
return;
}
}
System.out.println("Account number not found.");
}
}
static class BankAccount{
private int accountNum;
private String customerName;
private double balance;
private double[] transactions;
private String[] transactionsSummary;
private int numOfTransactions;
private static int noOfAccounts=0;
public String getAccountInfo(){
return "Account number: " + accountNum + "\nCustomer Name: " + customerName + "\nBalance:" + balance +"\n";
}
public String getTransactionInfo(int n)
{
String transaction = transactionsSummary[n];
if (transaction == null) {
return "No transaction exists with that number.";
}
else {
return transaction;
}
}
public BankAccount(String abc, double xyz){
customerName = abc;
balance = xyz;
noOfAccounts ++;
accountNum = noOfAccounts;
transactions = new double[100];
transactionsSummary = new String[100];
transactions[0] = balance;
transactionsSummary[0] = "A balance of : $" + Double.toString(balance) + " was deposited.";
numOfTransactions = 1;
}
public int getAccountNum(){
return accountNum;
}
public int getNumberOfTransactions() {
return numOfTransactions;
}
public void deposit(double amount){
if (amount<=0) {
System.out.println("Amount to be deposited should be positive");
} else {
balance = balance + amount;
transactions[numOfTransactions] = amount;
transactionsSummary[numOfTransactions] = "$" + Double.toString(amount) + " was deposited.";
numOfTransactions++;
}
}
public void withdraw(double amount)
{
if (amount<=0){
System.out.println("Amount to be withdrawn should be positive");
}
else
{
if (balance < amount) {
System.out.println("Insufficient balance");
} else {
balance = balance - amount;
transactions[numOfTransactions] = amount;
transactionsSummary[numOfTransactions] = "$" + Double.toString(amount) + " was withdrawn.";
numOfTransactions++;
}
}
}
}//end of class
}
To convert an integer to a String:
String out = Integer.toString(n);
You description of case 5 is
Print the detailed account information including last transactions
Just returning the number of transactions as a string is not going to achieve that.
You need to store every transaction as it happens in the transactions array in your BankAccount class and then get the last n values in that array in the gettransactionInfo() function.
EDIT:
And btw, you have forgotten to call the openNewAccount() function
Convert primitive int to its wrapper class and call its toString() method
public String gettransactionInfo(int n) {
return new Integer(n).toString();
}
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);
}
import javax.swing.JOptionPane;
import java.text.DecimalFormat;
public class CandleLine
{
public static void main(String[] args)
{
double dollars, answer;
int shipmentCode;
dollars = getPrice();
shipmentCode = getCode();
answer = getTotalPrice(dollars,shipmentCode);
output(answer,dollars);
finish();
}
public static double getPrice()
{
double price = 0.0;
boolean done = false;
while (!done)
{
String answer = JOptionPane.showInputDialog(null,"Enter the original price\n(do not use commas or dollar signs)\n or click Cancel to exit:");
if (answer == null) finish();
try
{
price = Double.parseDouble(answer);
if (price <= 0) throw new NumberFormatException();
else done = true;
}
catch(NumberFormatException e)
{
JOptionPane.showMessageDialog(null,"Your entry was not in the proper format.","Error",JOptionPane.INFORMATION_MESSAGE);
}
}
return price;
}
public static int getCode()
{
int code = 0;
boolean done = false;
while (!done)
{
try
{
String message = "Enter the shipment code:" + "\n\n1) Priority\n2) Express\n3) Standard\n\n";
code = Integer.parseInt(JOptionPane.showInputDialog(null,message));
if (code<1 || code>3) throw new NumberFormatException();
else done = true;
}
catch(NumberFormatException e)
{
JOptionPane.showMessageDialog(null,"Please enter a 1, 2, or 3.","Error",JOptionPane.INFORMATION_MESSAGE);
}
}
return code;
}
public static double getTotalPrice(double price, int shipmentcode)
{
double totalprice = 0.0;
switch(shipmentcode)
{
case 1:
totalprice = 14.95 + price;
break;
case 2:
totalprice = 11.95 + price;
break;
case 3:
totalprice = 5.95 + price;
break;
}
return totalprice;
}
public static void output(double totalprice, double price)
{
DecimalFormat twoDigits = new DecimalFormat("$#.00");
JOptionPane.showMessageDialog(null,"Your shipment fee is" + shipmentcode,"Shipment Fee",JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(null,"Your total cost is" + twoDigits.format(totalprice),"Price Total",JOptionPane.INFORMATION_MESSAGE);
}
public static void finish()
{
System.exit(0);
}
}
.
.
.
.
.
.
.
.
.
The case 3 needs to be zero when it total price exceeds $75 (no shipping cost over that price). How do I implement this?
case 3:
if (price > 75 ) {
totalPrice = price;
} else {
totalprice = 5.95 + price;
}
break;
So in total, how many possibilities are there for the shipping cost of an order?
final double [] shipmentprice = {14.95, 11.95, 5.95};
public static double getTotalPrice (final double price, final int shipmentcode)
{
return price + shipmentprice[shipmentcode -1];
}
A shorter code, but not very object oriented. I'm not sure whether I see an Enum rising. :)