Getting data from main program - java

I cannot figure out how to get the double balance1 in my main method to equal the double acctBal in my menu method. I assigned 0 to acctBal because i am not sure how to have it equivalent to whatever balance1 is. I put some asterisks next to the lines i am talking about.
public class ATM {
public static Scanner kbd;
public static void main(String[] args) {
String acctNum, acctPword;
String balance;
int x = 1;
kbd = new Scanner(System.in);
System.out.print("Enter your account number: ");
acctNum = kbd.nextLine();
System.out.print("Enter your account password: ");
acctPword = kbd.nextLine();
balance = checkID(acctNum, acctPword);
double balance1 = Double.parseDouble(balance);
System.out.println("You currently have $" + String.format("%.2f",balance1));*********************************
while (balance.equals("error") && x <4){
System.out.println("Wrong password try again.");
System.out.print("Enter your account password: ");
acctPword = kbd.nextLine();
x++;
}
if (x == 4)
System.out.println("Maximum number of attempts reached, Please try again later.");
if (x == 1){
menu();
}
kbd.close();
}
/**
* Determines if acctNum is a valid account number, and pwd is the correct
* password for the account.
* #param acctNum The account number to be checked
* #param pwd The password to be checked
* #return If the account information is valid, returns the current account
* balance, as a string. If the account information is invalid, returns
* the string "error".
*/
public static String checkID(String acctNum, String pwd)
{
String result = "error";
// Strings a, b, and c contain the valid account numbers and passwords.
// For each string, the account number is listed first, followed by
// a space, followed by the password for the account, followed by a space,
// followed by the current balance.
String a = "44567-5 mypassword 520.36";
String b = "1234567-6 anotherpassword 48.20";
String c = "4321-0 betterpassword 96.74";
if (acctNum.equals("44567-5") && pwd.equals("mypassword")){
result = "520.36";
return result;
}
if (acctNum.equals("1234567-6") && pwd.equals("anotherpassword")){
result = "48.20";
return result;
}
if (acctNum.equals("4321-0") && pwd.equals("betterpassword")){
result = "96.74";
return result;
}
return result;
}
public static void menu(){
int x = 0;
double acctBal = 0.0, deposit = 0.0, withAmnt = 0.0;**********this acctBal needs to equal balance1.
System.out.println("1. Display Balance \n2. Deposit\n3. Withdraw\n4. Log Out");
x = kbd.nextInt();
switch(x){
case 1:
displayBalance(acctBal);
break;
case 2:
deposit(acctBal, deposit);
break;
case 3:
withdraw(acctBal, withAmnt);
break;
case 4:
System.out.println("Have a nice day.");
break;
}
}
public static double deposit(double acctBal, double depAmnt){
System.out.print("How much money would you like to deposit? $");
depAmnt = kbd.nextDouble();
acctBal = acctBal + depAmnt;
System.out.println("Your balance is now at $" + String.format("%.2f", acctBal));
return acctBal;
}
public static double withdraw(double acctBal, double withAmnt){
System.out.print("How much money would you like to withdraw? $");
withAmnt = kbd.nextDouble();
if (acctBal <= 0){
System.out.println("You do not have any money.");
return acctBal;
}
if (acctBal < withAmnt){
System.out.print("You do not have enough money.\nHow much money would you like to withdraw? $");
withAmnt = kbd.nextDouble();
}
else{
acctBal = acctBal - withAmnt;
}
return acctBal;
}
public static double displayBalance(double balance){
System.out.println("Your balance is $" + String.format("%.2f", balance));
return balance;
}

You can change the menu() method to accept a parameter (called balance) and pass the value from main while calling menu() method, e.g.:
public static void menu(double acctBal){
double deposit = 0.0; //Other variables
}
And call it from main with balance, e.g.:
if (x == 1){
menu(balance);
}

Your code has a problem, you do not treat the situation where checkID returns "error". You cannot assign "error" to some String and then try to convert a double from that String.
Minor fix
balance = checkID(acctNum, acctPword);
double balance1 = 0.0;
if (balance.equals("error"))
{
// TODO: do something with invalid number.
}
else
{
balance1 = Double.parseDouble(balance);
}
System.out.println("You currently have $" + String.format("%.2f",balance1));

Related

Java Income Tax Calculator Need to add error message for any number that is 0 or less

I have a java project that is a Income tax calculator, and I am supposed to add a error message to it so that the program will not respond to a number that is 0 or less in the income prompt. I am just not sure where to put the prompt or what type of error message I need to accomplish this. Code:
import java.util.Scanner;
public class TaxCalculator {
static void calculate() {
// The tax rates for different types of customers.
final double RATE1 = 0.20;
final double RATE2 = 0.25;
final double RATE3 = 0.10;
final double RATE4 = 0.15;
final double RATE5 = 0.30;
final double RATE1_SINGLE_LIMIT = 1;
final double RATE2_MARRIED_LIMIT = 1;
final double RATE3_COHABITATING_LIMIT = 20000;
final double RATE4_COHABITATING_LIMIT = 50000;
double tax = 0;
Scanner in = new Scanner(System.in);
//Prompt for user to enter the customers income
System.out.print("Enter customer's income: ");
double income = in.nextDouble();
in.nextLine();
System.out.print("Please enter 's' for single, 'm' for married, or 'c' for cohabitating: ");
String maritalStatus = in.next();
in.nextLine();
// Where the taxes are calculated
if (maritalStatus.equals("s") && income > RATE1_SINGLE_LIMIT) {
tax = RATE1 * income;
} else if (maritalStatus.equals("m") && income > RATE2_MARRIED_LIMIT) {
tax = RATE2 * income;
} else if (maritalStatus.equals("c") && income <= RATE3_COHABITATING_LIMIT) {
tax = RATE3 * income;
} else if (maritalStatus.equals("c") && income <= RATE4_COHABITATING_LIMIT) {
tax = RATE4 * income;
} else {
tax = RATE5 * income;
}
System.out.print("Your income tax is: $" + tax);
}
// asks user if they would like to process another customer.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String newResponse = "";
do {
calculate();
System.out.println();
System.out.println("Process another response?. Please enter 'y' for yes, or 'n' for no: ");
newResponse = in.next();
in.nextLine();
} while (newResponse.equals("y"));
}
}
You could add the loops after printing appropriate prompts:
System.out.print("Enter customer's income: ");
double income;
while ((income = in.nextDouble()) <= 0) {
System.out.print("Income " + income + " is invalid. Please input correct income which must be greater than 0: ");
in.nextLine();
}
System.out.print("Please enter 's' for single, 'm' for married, or 'c' for cohabitating: ");
String maritalStatus;
while (!(maritalStatus = in.next()).matches("[smc]")) {
System.out.print("Marital status " + maritalStatus + " is invalid. Please input correct value: 's', 'm', or 'c': ");
in.nextLine();
}
Output:
Enter customer's income: -12
Income -12.0 is invalid. Please input correct income which must be greater than 0: -23
Income -23.0 is invalid. Please input correct income which must be greater than 0: 2300
Please enter 's' for single, 'm' for married, or 'c' for cohabitating: 1
Marital status 1 is invalid. Please input correct value: 's', 'm', or 'c': m

Account class error 2

I am still having trouble figuring out how the heck the most efficient way to do this is.. Basically, I am trying to make the balance = 0 for every object in the Account array created. I tried using a for loop and set balance = 0for each account created, but I am unsure of how to make this work since the balance variable is created in the class that has all of the methods. I have been trying to this problem all day, but no luck. Thanks.
Main method:
import java.util.Scanner;
import java.text.NumberFormat;
public class Account2
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
Account[] acct = new Account[30];
for (int count2; count2 < 30; count2++)
{
balance = 0; //Initial balance is always set to zero to be able to run fresh program every time
}
System.out.println("Enter your account number (1-30): ");
int key = scan.nextInt() - 1;
int reset = 0;
while (reset == 0)
{
System.out.println("Enter W for withdrawl; D for deposit; X to escape");
char choice = scan.next().charAt(0);
if (choice == 'W' || choice == 'w' || choice == 'D' || choice == 'd' || choice == 'x' || choice == 'X')
{
if (choice == 'W' || choice == 'w')
{
System.out.println("Enter amount to withdraw: ");
Double withdraw1 = scan.nextDouble();
if (withdraw1 <= acct[key].getBalance())
{
acct[key].withdraw(withdraw1);
System.out.println("User # " + key++ + " funds after withdraw: " + acct[key].getBalance() + "$");
System.out.println("User # " + key++ + " funds after interest: " + acct[key].addInterest() + "$");
reset++;
}
else
System.out.println("Insufficient funds.");
}
if (choice == 'D' || choice == 'd')
{
System.out.println("Enter amount to deposit: ");
Double deposit1 = scan.nextDouble();
if (deposit1 > 0)
{
acct[key].deposit(deposit1);
System.out.println("User # " + key++ + " funds after deposit: " + acct[key].getBalance() + "$");
System.out.println("User # " + key++ + " funds after interest: " + acct[key].addInterest() + "$");
reset++;
}
else
System.out.println("Use the withdrawl feature to withdrawl money.");
}
if (choice == 'x' || choice == 'X')
System.out.println("Thank You for using this bank.");
reset++;
}
else
{
System.out.println("Invalid entry, please try again");
reset = 0;
}
}
}
}
Supporting class:
public class Account
{
private final double RATE = 0.03; //Interest is 3%
private int acctNumber;
private String name;
private balance;
//Defines owner, account number, and initial balance.
public Account(String owner, int account, double initial)
{
name = owner;
acctNumber = account;
balance = initial;
}
//deposits a specified amount and returns new balance
public double deposit(double amount)
{
balance = balance + amount;
return balance;
}
//withdraws the specified amount from the account and applies the fee
// + returns balance
public double withdraw(double amount)
{
int fee = 1;
balance = balance - amount - fee;
return balance;
}
//Adds interest to the account
public double addInterest()
{
balance += (balance * RATE);
return balance;
}
public double getBalance()
{
return balance;
}
//returns a one line description of the account as a string
public String toString()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
return acctNumber + "/t" + name + "/t" + fmt.format(balance);
}
}
From an outside class, you can only interact with Account in the way exposed in its visible (e.g. public) API.
In this case, the current way to do this would be to withdraw() the current balance:
acct[i].withdraw(acct[i].getBalance());
Though this specific case would put the balance into the negatives because you charge a fee for a withdrawal (which is hidden from the calling class).
If you were to expose a setBalance method on Account, you could instead do
acct[i].setBalance(0);
However on closer look, it seems like what you are having trouble with is actually initializing the array of accounts. You can do this like this:
for (int count2; count2 < 30; count2++)
{
acct[count2] = new Account(owner, count2, 0);
}

Error: Non-static variable inout cannot be referenced from a static context

I am working on a program for my CS class that involves methods and variables. I know it's a problem with the scope, or at least I think, but not sure how to solve. I can't use objects. The code isn't complete yet, because I'm currently just focused on this one problem.
import java.util.Scanner;
public class MethodBankingSystem {
Scanner input = new Scanner(System.in);
public static double Deposit(double userDeposit, double userBalance) {
System.out.print("Enter the amount you would like to deposit: ");
userDeposit = input.nextDouble(); //Create variable userDeposit for amount entered
userBalance = userBalance + userDeposit; //Replace value for userBalance
System.out.printf("New balance after deposit is: $" + "%.2f \n\n",userBalance );
return userBalance;
}
public static double Withdraw(double userWithdraw, double userBalance) {
System.out.print("Enter the amount you would like to withdraw: ");
userWithdraw = input.nextDouble(); //Create variable userWithdraw for amount entered
if (userWithdraw > userBalance) { //Create if/else statement to make sure enough funds are available
System.out.printf("Funds are not available for this withdraw \n\n");
}
else {
userBalance = userBalance - userWithdraw; //Replace value for userBalance
System.out.printf("New balance after withdraw is: $" + "%.2f \n\n",userBalance );
}
return userBalance;
}
public static void CurrentBalance(double userBalance) {
System.out.printf("Current balance is $" + "%.2f \n\n",userBalance );
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double userBalance = 100.00;
double userDeposit;
double userWithdraw;
double userInput;
String cardNumber;
String menu = "Welcome to Mustang Bank\nPlease choose from the options below:\n1 - Make a Deposit\n" +
"2 - Make a Withdraw\n3 - Check your Current Balance\n9 - Exit the Program\nEnter Option:\n";
do {
System.out.print(menu);
userInput = input.nextDouble();
switch (userInput) {
case '1':
Deposit(userDeposit, userBalance);
break;
case '2':
Withdraw(userWithdraw, userBalance);
break;
case '3':
CurrentBalance(userBalance);
break;
case '4':
CurrentBalance(userBalance);
break;
default:
System.out.println("This option is not acceptable.");
}
} while (userInput !=9);
}
}
Basically the problem is this:
static means that there is only one instance of that field per class (not instance). The field is essentially shared between all instances; modifying it in one instance will affect it in all instances. You can reference static fields within instances but you cannot statically reference instance members.
Either make input static (not really recommended):
static Scanner input = new Scanner(System.in);
Or make an instance of MethodBankingSystem and remove the static modifiers from your methods (this is what I think you are trying to do):
import java.util.Scanner;
public class MethodBankingSystem {
Scanner input = new Scanner(System.in);
public double Deposit(double userDeposit, double userBalance) {
System.out.print("Enter the amount you would like to deposit: ");
userDeposit = input.nextDouble(); //Create variable userDeposit for amount entered
userBalance = userBalance + userDeposit; //Replace value for userBalance
System.out.printf("New balance after deposit is: $" + "%.2f \n\n",userBalance );
return userBalance;
}
public double Withdraw(double userWithdraw, double userBalance) {
System.out.print("Enter the amount you would like to withdraw: ");
userWithdraw = input.nextDouble(); //Create variable userWithdraw for amount entered
if (userWithdraw > userBalance) { //Create if/else statement to make sure enough funds are available
System.out.printf("Funds are not available for this withdraw \n\n");
}
else {
userBalance = userBalance - userWithdraw; //Replace value for userBalance
System.out.printf("New balance after withdraw is: $" + "%.2f \n\n",userBalance );
}
return userBalance;
}
public void CurrentBalance(double userBalance) {
System.out.printf("Current balance is $" + "%.2f \n\n",userBalance );
}
public static void main(String[] args) {
new MethodBankingSystem();
}
MethodBankingSystem () {
Scanner input = new Scanner(System.in);
double userBalance = 100.00;
double userDeposit;
double userWithdraw;
double userInput;
String cardNumber;
String menu = "Welcome to Mustang Bank\nPlease choose from the options below:\n1 - Make a Deposit\n" +
"2 - Make a Withdraw\n3 - Check your Current Balance\n9 - Exit the Program\nEnter Option:\n";
do {
System.out.print(menu);
userInput = input.nextDouble();
switch (userInput) {
case '1':
Deposit(userDeposit, userBalance);
break;
case '2':
Withdraw(userWithdraw, userBalance);
break;
case '3':
CurrentBalance(userBalance);
break;
case '4':
CurrentBalance(userBalance);
break;
default:
System.out.println("This option is not acceptable.");
}
} while (userInput !=9);
}
}
I FIXED YOUR CODE GET IT BEFORE THE QUESTION GETS DELETED
Because I'm a nice guy I fixed your code. There were all sorts of issues, please read up on them. You create an instance of input twice, you are switching on a double you are calling Deposit(userDeposit, userBalance); without initialisinguserDeposit, you declare cardNumber but never instantiate or even try to use it anywhere, you have issues with static scoping.
import java.util.Scanner;
public class MethodBankingSystem {
public static void main(String[] args) {
new MethodBankingSystem();
}
Scanner input;
double userBalance = 100.00;
MethodBankingSystem() {
input = new Scanner(System.in);
int userInput;
String menu = "Welcome to Mustang Bank\nPlease choose from the options below:\n" + "1 - Make a Deposit\n"
+ "2 - Make a Withdraw\n" + "3 - Check your Current Balance\n"
+ "9 - Exit the Program\nEnter Option:\n";
do {
System.out.print(menu);
userInput = input.nextInt();
switch (userInput) {
case 1:
Deposit();
break;
case 2:
Withdraw();
break;
case 3:
CurrentBalance();
break;
case 9:
break;
default:
System.out.println("This option is not acceptable.");
}
} while (userInput != 9);
input.close();
}
public double Deposit() {
System.out.print("Enter the amount you would like to deposit: ");
double userDeposit = input.nextDouble(); // Create variable userDeposit for amount entered
userBalance = userBalance + userDeposit; // Replace value for userBalance
System.out.printf("New balance after deposit is: $" + "%.2f \n\n", userBalance);
return userBalance;
}
public double Withdraw() {
System.out.print("Enter the amount you would like to withdraw: ");
double userWithdraw = input.nextDouble(); // Create variable userWithdraw for amount entered
if (userWithdraw > userBalance) { // Create if/else statement to make sure enough funds are available
System.out.printf("Funds are not available for this withdraw \n\n");
} else {
userBalance = userBalance - userWithdraw; // Replace value for userBalance
System.out.printf("New balance after withdraw is: $" + "%.2f \n\n", userBalance);
}
return userBalance;
}
public void CurrentBalance() {
System.out.printf("Current balance is $" + "%.2f \n\n", userBalance);
}
}

How would I have test code to test if an input has characters instead of numbers

public void deposit (double amount){
if (amount >= 0) {
balance = balance + amount;
} else {
System.out.println("Your deposit is a negative number, If you would like to withdraw please enter '0' and select Withdraw.");
}
while (!double || !int) {
System.out.println("Invalid Input. Try again");
}
}
This is the code, I am trying to get to test whether or not a user input entered in another class file has a character other than an integer or double. I need for this piece of code to work here and with a withdraw class that I have already created underneath this one, I figured if it I can get it to work in one it will work in the other.
Thanks in advance!
Here is the code Requested:
import java.util.Scanner;
public class Bank {
double balance = 0;
Scanner in = new Scanner(System.in);
int userChoice;
BankAccount account1 = new BankAccount();
boolean quit = false; {
do {
System.out.println("Your Choice: ");
System.out.println("For Deposit type 1");
System.out.println("For Withdraw type 2");
System.out.println("For Check Balance type 3");
System.out.println("Type 0 to quit");
userChoice = in.nextInt();
switch (userChoice){
case 1:
//Deposit Money
System.out.println("How Much would you like to deposit?");
double amount;
amount = in.nextDouble();
System.out.println("Depositing: " + amount);
account1.deposit(amount);
//balance = amount + balance;
break;
case 2:
//Withdraw money
System.out.println("How much would you like to withdraw?");
amount = in.nextDouble();
System.out.println("Withdrawing: " + amount);
account1.withdraw(amount);
//balance = balance - amount;
break;
case 3:
//check balance
System.out.println("Checking Balance.");
account1.getBalance();
System.out.println(account1.balance);
break;
case 0:
System.out.println("Thanks for Using BankAccount Banking System!");
quit = true;
break;
default:
System.out.println("Error: Choice not recognized please choose again.");
continue;
}
if (userChoice == 0)
quit = true;
}while
(!quit);
}
}
And here is the entirety of the first portion of code:
public class BankAccount {
public double balance;
public int sufficientFunds = 1;
public int insufficientFunds = -1;
public BankAccount(){
balance = 0;
}
public BankAccount (double initialBalance){
balance = initialBalance;
}
public void deposit (double amount){
if (amount >= 0) {
balance = balance + amount;
} else {
System.out.println("Your deposit is a negative number, If you would like to withdraw please enter '0' and select Withdraw.");
}
while (!double || !int) {
System.out.println("Invalid Input. Try again");
}
}
public double withdraw (double amount){
balance = balance - amount;
if (balance == amount){
return sufficientFunds;
}else if (balance > amount){
return sufficientFunds;
}else if (balance < amount){
System.out.println("INSUFFICENT FUNDS");
return insufficientFunds;
}
return amount;
}
public double getBalance(){
return balance;
}
}
Java is a strongly typed language, so there is no chance that the amount variable could contain anything other than a double, which is a number.
Use this for bank
import java.util.Scanner;
public class Bank {
double balance = 0;
Scanner in = new Scanner(System.in);
int userChoice;
BankAccount account1 = new BankAccount();
boolean quit = false;
public void thisShouldBeAMethod(){
do {
System.out.println("Your Choice: ");
System.out.println("For Deposit type 1");
System.out.println("For Withdraw type 2");
System.out.println("For Check Balance type 3");
System.out.println("Type 0 to quit");
//userChoice = in.nextInt();
String regex = "[0-9]+";
String input = in.next();
if(input.matches(regex)){
userChoice = Integer.parseInt(input);
switch (userChoice) {
case 1:
// Deposit Money
System.out.println("How Much would you like to deposit?");
double amount;
amount = in.nextDouble();
System.out.println("Depositing: " + amount);
account1.deposit(amount);
// balance = amount + balance;
break;
case 2:
// Withdraw money
System.out.println("How much would you like to withdraw?");
amount = in.nextDouble();
System.out.println("Withdrawing: " + amount);
account1.withdraw(amount);
// balance = balance - amount;
break;
case 3:
// check balance
System.out.println("Checking Balance.");
account1.getBalance();
System.out.println(account1.balance);
break;
case 0:
System.out
.println("Thanks for Using BankAccount Banking System!");
quit = true;
break;
default:
System.out
.println("Error: Choice not recognized please choose again.");
continue;
}
if (userChoice == 0)
quit = true;
}
else{
System.out.println("Invalid Input. Try again");
}
} while (!quit);
}
}
update this in BankAccount
public void deposit (double amount){
if (amount >= 0) {
balance = balance + amount;
} else {
System.out.println("Your deposit is a negative number, If you would like to withdraw please enter '0' and select Withdraw.");
}
// while (!double || !int) {
// System.out.println("Invalid Input. Try again");
// }
}
And test
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
Bank bank = new Bank();
bank.thisShouldBeAMethod();
}
}
Ok, so when accepting the input for amount, surround it with a try-catch block so that instead of simply
amount = in.nextDouble();
you'll get
try{
amount = in.nextDouble();
}catch(InputMismatchException ime){
//What to do if this is not a numerical value
}
Additionally you'll want to wrap that in a do-while loop so that the program asks again until a valid input is accepted:
boolean inputInvalid;
double amount;
do{
System.out.println("How Much would you like to deposit?");
try{
amount = in.nextDouble();
inputInvalid = false;
}catch(InputMismatchException ime){
//What to do if this is not a numerical value
inputInvalid = true;
}
}while(inputInvalid);
Edit: due to the in.nextDouble(), the program may be continuously trying to read the \n in the buffer (which is when the user presses Enter). To avoid this, right after initializing the Scanner object (or first thing in a method if it's a class variable), add
in.useDelimiter("\n");
To the Java to end the input at that and ignore the newline character.

Creating a Bank program [closed]

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();
}

Categories