My problem regards loops and exceptions. If i run this programma it will take me to point 1, but it only let's me put in a string and then just stops. Whereas I want it to continue, just as it initially did. What am I doing wrong?
while (true) {
try {
//From here I want to start everytime. Point 1
System.out.println("Do you whish to deposit or withdraw money or end the transaction?");
Scanner readerBankTransactions = new Scanner(System.in);
String BankTransaction = readerBankTransactions.nextLine();
if (BankTransaction.equalsIgnoreCase(Transactions.ENDTRANSACTION.toString())) {
System.out.println("Thank you for using our service.");
break; //The programma should terminate here
} else {
while (true) {
if (BankTransaction.equalsIgnoreCase(Transactions.DEPOSIT.toString())) {
System.out.println("How much do you whish to deposit?");
Scanner readerDeposit = new Scanner(System.in);
double deposit = readerDeposit.nextDouble();
rekening.deposit(deposit);
double balance = rekening.getBalance();
System.out.println("Your balance is now: " + balance);
readerDeposit.close();
break; //from here I want to start again at point 1.
} else if (BankTransaction.equalsIgnoreCase(Transactions.WITHDRAW.toString())) {
System.out.println("How much do you whish to withdraw?");
Scanner readerWithdraw = new Scanner(System.in);
double withdraw = readerWithdraw.nextDouble();
rekening.withdraw(withdraw);
double balance = rekening.getBalance();
System.out.println("Your balance is now: " + balance);
readerWithdraw.close();
break; //from here I want to start again at point 1.
}
readerBankTransactions.close();
readerbankAccountNumber.close();
}
} continue;
} catch (InputMismatchException | NumberFormatException exception1) {
System.out.println("This is not what you should have put in");
} catch (InsufficientFundsException exception2) {
System.out.println("insufficientfunds!");
} catch (MaximumWithdrawException exception3) {
System.out.println("Maximum withdraw restriction!");
}
}
}
Some suggestions:
Try to avoid the pattern of while (true) followed by continue or break statements. It makes the logic very hard to follow.
You should isolate some of the logic in helper methods. Again, this will make the main logic easier to follow.
I don't understand the purpose of the inner while loop. What are you trying to accomplish here?
With that, here's my suggested rewrite:
do {
try {
String BankTransaction = getInitialSelection();
if (isDepositRequest(BankTransaction)) {
handleDeposit();
} else if (isWithdrawalRequest(BankTransaction)) {
handleWithdrawal();
}
} catch (InputMismatchException | NumberFormatException exception1) {
System.out.println("This is not what you should have put in");
} catch (InsufficientFundsException exception2) {
System.out.println("insufficientfunds!");
} catch (MaximumWithdrawException exception3) {
System.out.println("Maximum withdraw restriction!");
}
} while (!isExitRequest(BankTransaction));
System.out.println("Thank you for using our service.");
This is assuming definitions of handleDeposit(), handleWithdrawal() matching the corresponding code in your original code.
Also, I've assumed the following helper methods:
private boolean isDepositRequest(String bankTransaction) {
return Transactions.DEPOSIT.toString().equalsIgnoreCase(bankTransaction);
}
private boolean isWithdrawalRequest(String bankTransaction) {
return Transactions.WITHDRAW.toString().equalsIgnoreCase(bankTransaction);
}
private boolean isExitRequest(String bankTransaction) {
return Transactions.ENDTRANSACTION.toString().equalsIgnoreCase(bankTransaction);
}
What you are looking for is called a labelled break. Take a look information on labelled breaks at : https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
Use a label for your outer while loop for eg point1 : and in the place where you want to restart from point 1 use break point1;
Related
I want it to start again at the most outer for loop, so that if a user messes up the input, they can sign in again and everything work just like if the program started all over again. I tried using continue statements and break statements and using the nicknames for the loops. Like
outer: do {
//loop code
}
then break outer;
The problem is when I do that, it messes up my controlling of the loop. The end statement that asks the user if they want to go back to the main menu. Right now I just have the app exit, if an exception is encountered, using return statement, but If I'm just gonna exit, I might as well just let the app crash. I want to actually resolve the situation and ask the user for valid input.
package main;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.Scanner;
import model.BankAccount;
public class app {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
HashMap<String, BankAccount> accounts = new HashMap<>();
BankAccount sallyAccount = new BankAccount(1000);
BankAccount bobAccount = new BankAccount(2000);
BankAccount naomiAccount = new BankAccount();
accounts.put("Sally", sallyAccount);
accounts.put("Bob", bobAccount);
accounts.put("Naomi", naomiAccount);
String name;
BankAccount account;
int userInput;
double amount;
boolean again;
do
{
again = true;
System.out.println("Login: Enter your name.");
name = console.next();
account = accounts.get(name);
if(account == null)
{
System.out.println("Please enter a valid name.");
return;
}
do
{
System.out.println("1 - Deposit");
System.out.println("2 - Withdraw");
System.out.println("3 - View Balance");
System.out.println("4 - Logout");
userInput = console.nextInt();
switch(userInput)
{
case 1:
System.out.println("Enter amount to deposit: ");
try
{
amount = console.nextDouble();
}
catch(InputMismatchException e)
{
System.out.println("Please enter a numeric amount.");
return;
}
if(amount < 0)
{
System.out.println("You can't withdraw a negative amount");
return;
}
account.deposit(amount);
break;
case 2:
System.out.println("Enter amount to withdraw: ");
try
{
amount = console.nextDouble();
}
catch(InputMismatchException e)
{
System.out.println("Please enter a numeric amount.");
return;
}
if(amount < 0)
{
System.out.println("You can't withdraw a negative amount");
return;
}
account.withdraw(amount);
break;
case 3:
System.out.println(account.getBalance());
break;
case 4:
again = false;
break;
default:
System.out.println("Enter a valid option.");
}
}
while(again);
System.out.println("Back to main menu? 1 - Yes, 2 - No");
try
{
userInput = console.nextInt();
}
catch(InputMismatchException e)
{
System.out.println("Please enter a number");
return;
}
}
while(userInput == 1);
}
}
package model;
public class BankAccount {
private double balance = 0;
public BankAccount() {}
public BankAccount(double balance)
{
this.balance = balance;
}
public void deposit(double amount)
{
balance = balance + amount;
}
public void withdraw(double amount)
{
if((balance - amount) < 0)
{
System.out.println("Transaction Failed: You can't withdraw more than you have.");
}
else
{
balance = balance - amount;
}
}
public double getBalance()
{
return balance;
}
}
You'll be best served by breaking up your main function in multiple functions that handle different parts of the control logic. A good rule of thumb (for beginning programmers) is a function over ~10-15 lines should probably be multiple functions, though it's not an ironclad rule.
I rewrote your program to be multiple functions, but since this seems like a homework problem I won't post the whole thing. Rather, a general strategy with some snippets.
For example, when the user enters an amount to deposit or withdraw. What your programs wants in that moment is a single double, so you could request a single double, and let another method figure out how to get it:
switch (getMenuChoice()) {
case 1:
account.deposit(getDepositOrWithdrawAmount("deposit"));
break;
case 2:
account.withdraw(getDepositOrWithdrawAmount("withdraw"));
break;
// etc.
}
Then, that function is responsible for looping infinitely until the user provides a valid value:
static double getDepositOrWithdrawAmount(String depositOrWithdraw) {
// loop infinitely until we get a valid value
while (true) {
System.out.println("Enter amount to " + depositOrWithdraw);
try {
double amount = console.nextDouble();
if (amount < 0) {
System.out.println("You can't " + depositOrWithdraw + " a negative amount.");
} else {
// valid value! return for deposit / withdraw to use
// , ending the infinite loop
return amount;
}
} catch (InputMismatchException e) {
System.out.println("Please enter a numeric amount.");
// clear the bad token from the stream
// if you don't do this, each time you
// call `nextDouble`, the same value will
// be returned, causing an infinite loop
console.next();
}
}
}
The nice thing about this function is it works in isolation:
public static void main(String[] args) {
System.out.println("Test: " + getDepositOrWithdrawal("test!"));
}
Gives this result:
Enter amount to test!
abc
Please enter a numeric amount.
Enter amount to test!
not-a-number
Please enter a numeric amount.
Enter amount to test!
-5
You can't test! a negative amount.
Enter amount to test!
1000
Test: 1000.0
This lets you test that pieces of your program are working on their own, instead of trying to debug one big program.
You can write other parts of your program as functions as well, but I'll leave that to you.
So I am getting an error in eclipse (Unreachable code). I think it may be because I am calling an objects method inside a while loop. However I need to declare it during the while loop as the users input has to meet some requirements.
Here is the segment of code from the main method:
double startMoney = 0;
AccountBasic PrimaryAccount = new AccountBasic(startMoney);
System.out.println("How much £ would you like to begin with in the format of £0000.00?");
startMoney = input.nextDouble();
while (true) {
PrimaryAccount.deposit(startMoney);
}
System.out.println("Your available balance is £" + PrimaryAccount.getBalance()); //unreachable code
Here is the code from the objects class:
public class AccountBasic extends StockAccount
{
public AccountBasic(double initialBalance)
{
super(initialBalance);
}
public void withdraw(double amount)
{
balance -= amount;
}
public void deposit(double amount)
{
while (true)
{
if (amount > 500)
{
System.out.println("Please deposit an amount between £1 - £500");
continue;
}
else if (amount <= 500)
{
balance += amount;
break;
}
}
}
public double getBalance()
{
return balance;
}
}
The code is unreachable because you have a while loop that will run indefinitely, into the end of time. a while loop that runs while true is equal to true. Try changing the while loop so that it ends or get rid of it totally.
You're getting an unreachable code error due to this block of code:
while (true) {
PrimaryAccount.deposit(startMoney);
}
This loop will always evaluate to true (obviously) and therefore run forever, as you provided no means of breaking out of the loop.
The while loop will never stops.[Infinite Loop]
while (true) {
PrimaryAccount.deposit(startMoney);
}
Make it stop by updating condition or using break statement
You have an infinite loop
while(true)//Condition is always true
So, there is no way to exit that loop, so code after that loop will never execute.
Provide way to exit loop either break or change condition.
I think you may return a Boolean of the method "deposit", remove the while true from there and return if the deposit is correct. Like that:
public boolean deposit(double amount)
{
if (amount > 500) {
System.out.println("Please deposit an amount between £1 - £500");
return false;
}
else if (amount <= 500) {
balance += amount;
return true
}
}
And then you can make you loop asking for an input like that:
while (true) {
startMoney = input.nextDouble();
if (PrimaryAccount.deposit(startMoney)) {
break;
} else {
continue;
}
}
PS: usually we use the camel case naming convention so your variable "PrimaryAccount" will be better named like that:
AccountBasic primaryAccount = new AccountBasic(startMoney);
I have this bit of code to return to the beginning of the program if an answer is not expected.
...
else // returns to start for unsatisfactory
{
System.out.println();
System.out.println();
System.out.println("Check your spelling and try again");
main (args);
}
...
however when I enter a different word then go through again and enter an expected word the program outputs two different results
Current Salary: $100.00
Amount of your raise: $4.00
Your new salary: $104.00
Current Salary: $100.00
Amount of your raise: $0.00
Your new salary: $100.00
I tried using an else if statement to possibly eliminate that as a cause but it caused the same thing.
import java.util.Scanner;
import java.text.NumberFormat;
public class Salary {
public static void main (String[] args) {
double currentSalary; // employee's current salary
double raise = 0.0; // amount of the raise
double newSalary; // new salary for the employee
String rating; // performance rating
Scanner scan = new Scanner(System.in);
System.out.print ("Enter the current salary: ");
currentSalary = scan.nextDouble();
System.out.print ("Enter the performance rating (Excellent, Good, or Poor): ");
rating = scan.next();
// Computes raise with if-else
if ((rating.equals("Excellent")) || (rating.equals("excellent"))) {
// calculates raise for excellent
raise = .06 * currentSalary;
}
else if ((rating.equals("Good")) || (rating.equals("good"))) {
// calculates raise for good
raise = .04 * currentSalary;
}
else if ((rating.equals("Poor")) || (rating.equals("poor"))) {
// calculates raise for poor
raise = .015 * currentSalary;
}
else {
// returns to start for unsatisfactory
System.out.println();
System.out.println();
System.out.println("Check your spelling and try again");
main (args);
}
newSalary = currentSalary + raise;
// Print the results
NumberFormat money = NumberFormat.getCurrencyInstance();
System.out.println();
System.out.println("Current Salary: " + money.format(currentSalary));
System.out.println("Amount of your raise: " + money.format(raise));
System.out.println("Your new salary: " + money.format(newSalary));
System.out.println();
}
}
That is because you call main recursively (which is not considered good practice BTW) when you don't get an expected input. After you enter (the 2nd time) an expected input, the remainder of the initial main must still be executed which will then work with a raise of 0.0 as the input was invalid.
A pragmatic solution for your issue could be avoiding the recursive call to main and wrap e.g. the input validation in a loop like so
...
System.out.print ("Enter the performance rating (Excellent, Good, or Poor): ");
while (true) {
rating = scan.next();
if ((rating.equals("Excellent")) || (rating.equals("excellent")))
{
raise = .06 * currentSalary; break;
}
else if ((rating.equals("Good")) || (rating.equals("good")))
{
raise = .04 * currentSalary; break;
}
else if ((rating.equals("Poor")) || (rating.equals("poor")))
{
raise = .015 * currentSalary; break;
}
else
{
System.out.println();
System.out.println();
System.out.println("Check your spelling and try again");
}
}
...
You're not returning after you call main (args); so every iteration of your program will continue.
You should add return; after main (args);
{
System.out.println();
System.out.println();
System.out.println("Check your spelling and try again");
main (args);
return;
}
edit: as pointed out by John3136 you shouldn't be calling main (args) recursively either.
That (second) call you make to main() "finishes" and comes back out to the "first" one that was invoked by starting the program.
So the first lot of results are from your explicit call to main(). The second lot is from when that call ends and you are back to where you called from.
Calling main() recursively is not recommended. You should use a while loop inside main(). i.e. Keep asking for input until you know the input is valid, and then actually use it.
You should not call main recursively.you should use do while loop as I update code and it's working fine.
import java.util.Scanner;
import java.text.NumberFormat;
public class Salary {
public static void main (String[] args) {
double currentSalary; // employee's current salary
double raise = 0.0; // amount of the raise
double newSalary; // new salary for the employee
String rating; // performance rating
boolean flag=false; // to check input
Scanner scan = new Scanner(System.in);
do{
System.out.print ("Enter the current salary: ");
currentSalary = scan.nextDouble();
System.out.print ("Enter the performance rating (Excellent, Good, or Poor): ");
rating = scan.next();
// Computes raise with if-else
if ((rating.equals("Excellent")) || (rating.equals("excellent"))) // calculates raise for excellent
{
raise = .06 * currentSalary;
flag=true;
}
else if ((rating.equals("Good")) || (rating.equals("good"))) // calculates raise for good
{
raise = .04 * currentSalary;
flag=true;
}
else if ((rating.equals("Poor")) || (rating.equals("poor"))) // calculates raise for poor
{
raise = .015 * currentSalary;
flag=true;
}
else // returns to start for unsatisfactory
{
System.out.println();
System.out.println();
System.out.println("Check your spelling and try again");
flag=false;
}
}while(!flag);
newSalary = currentSalary + raise;
// Print the results
NumberFormat money = NumberFormat.getCurrencyInstance();
System.out.println();
System.out.println("Current Salary: " + money.format(currentSalary));
System.out.println("Amount of your raise: " + money.format(raise));
System.out.println("Your new salary: " + money.format(newSalary));
System.out.println();
}
}
You may want to consider another approach. Either terminate the problem in case the input is invalid or try to repair it. The following example is for the "repair" approach,
public class Salary {
public static void main(String[] args) {
IPM ipm;
if (verify(args)) {
ipm = new IPM(args);
} else {
Scanner scan = new Scanner(System.in);
String[] update;
do {
update = repair(scan);
} while (!verify(update)); // You may want a loop count as well...
ipm = new IPM(update);
}
ipm.print();
}
public static boolean verify(String[] s) {
return IPM.verify(s);
}
public static String[] repair (Scanner s) {
// Request new input and store it in an array of strings.
// This method does not validate the input.
}
}
public class IPM {
double currentSalary;
double raise = 0.0;
double newSalary;
String rating;
IPM(String[] input) {
// Set attributes of IPM.
}
public static boolean verify(String[] s) {
//Determine if the input is valid.
}
public void print() {
// Print IPM object.
}
}
Note that the call to IPM.verify() from salary. This should be a part of the responsibility of IPM since Salary is not require to know anything about main. Also, the class IPM might change and a call to IPM.verify() will not require that all classes which verifies the IPM are changed as well.
In my program, users enter values and those get stored in arrayList. ArryList objects are written into a file. I have used file-i/o, object-i/o stream for writing and readin in file.Now I want to perform addition and subtraction among the objects (int or double). That is withdrawing money from one account should be added with another account, and their value must be subtracted and added with the particular acount's amount. And finally I want that value must be updated so that it can print out and show the current status. How could I do that?
This is the main class:
public class BankApp_Assignment {
//static int numOfAcc = 0;
public static void main(String[] args) {
System.out.println("WELCOME TO OUR BANK!\n\n");
List<BankAccount> bankAccounts = new ArrayList<BankAccount>();
List<BankAccount> bankAccounts2 = new ArrayList<BankAccount>();
ReaderWriter rw=new ReaderWriter();
while (true) {
System.out.println("Choose your option:\n"
+ "1. Create new account\n"
+ "2. Deposit/withdraw\n"
+ "3. View One account\n"
+ "4. Deleting an account\n"
+ "5. View all the accounts\n"
+ "6. Return to menu\n");
System.out.println("*************\n"
+ "************");
option1 = sc.nextInt();
sc.nextLine();
//switch-case starts
switch (option1) {
case 1:
//create account
BankAccount bankAcc = new BankAccount();
System.out.println("Enter Full Name:");
bankAcc.setName(sc.nextLine());
System.out.println("Choose an Account Number:");
bankAcc.setAccNum(sc.nextInt());
System.out.println("Choose the initial amount:");
bankAcc.setInitiateAmount(sc.nextDouble());
//adding those into the arrayList
bankAccounts.add(bankAcc);
rw.writeToFile(bankAccounts);
System.out.println("-------------\n"
+ "-------------");
break;
case 2:
bankAccounts2=(List<BankAccount>)rw.readFromFile();
//First displaying the current accouns info
System.out.println("Name \tAccount No \tInitial Amount");
for (BankAccount bankAccount : bankAccounts2) {
System.out.println(bankAccount);
}
System.out.println("\t\t.........\n"
+ "\t\t.........");
System.out.println("To transfer money within the bank accounts enter 1\n"
+ "To deposit/withdraw money in the same account enter 2");
option2 = sc.nextInt();
sc.nextLine();
//inner switch-case starts
switch (option2) {
case 1:
/*
BankAccount is the class for setter and getter
bankAccounts2 is the arrayList for reading objects from file
*/
bankAccounts2 = (List<BankAccount>) rw.readFromFile();
BankAccount fromAcc = null;
BankAccount toAcc = null;
System.out.println("Enter the account number you want to withdraw from:");
withdraw_accNum = sc.nextInt();
System.out.println("Enter the amount you want to withdraw:");
withdraw_amount = sc.nextDouble();
System.out.println("Enter the account number you want to deposit to:");
deposit_accNum = sc.nextInt();//the deposit amount is alwyas the same as withdraw_amount
//find the matching acc number:withdraw_accNum
for (BankAccount listItemsFirst : bankAccounts2) {
//if the withdraw acc num matches with the given one
if (listItemsFirst.getAccNum() == withdraw_accNum) {
//store it
fromAcc = listItemsFirst;
break;
}
}
//find the matching acc number: deposit_accNum
for (BankAccount listItemsSec : bankAccounts2) {
//if the withdraw acc num matches with the given one
if (listItemsSec.getAccNum() == deposit_accNum) {
//store it
toAcc = listItemsSec;
break;
}
}
//if the withdraw amount is bigger than the current balance
if (withdraw_amount > fromAcc.getInitialAmount()) {
System.out.println("Withdrawing Amount was bigger than the Initial amount.\nChoose the menu again. .");
break;
}
//subtracting and adding the withdrawn amount
fromAcc.setInitiateAmount(fromAcc.getInitialAmount() - withdraw_amount);
toAcc.setInitiateAmount(toAcc.getInitialAmount() + withdraw_amount);
System.out.println("DONE!\t print them out to see the current status.");
System.out.println("");
break;
case 2://deposit/withdraw money in the same accounts
bankAccounts2=(List<BankAccount>)rw.readFromFile();
BankAccount fromAcc_SameAcc = null;
BankAccount toAcc_SameAcc = null;
System.out.println("Enter the account number you want to deposit or withdraw from:");
//read the accNum
depOrWithAccountNum = sc.nextInt();
System.out.println("Enter the amount (To withdraw enter a negative value)");
//read the amount
depOrWithAmount = sc.nextDouble();
//checking the matching account number in arrayList
for (BankAccount listItemsThird : bankAccounts2) {
if (listItemsThird.getAccNum() == depOrWithAccountNum) {
fromAcc_SameAcc = listItemsThird;
break;
}
}
if (depOrWithAmount - 1 < fromAcc_SameAcc.getInitialAmount()) {
System.out.println("Withdraw amount is bigger than the current amount.\nChoose the menu again. .");
break;
}
if (depOrWithAmount < 0) {//the amount is negative
fromAcc_SameAcc.setInitiateAmount(fromAcc_SameAcc.getInitialAmount() + depOrWithAmount);
} else {
fromAcc_SameAcc.setInitiateAmount(fromAcc_SameAcc.getInitialAmount() + depOrWithAmount);
}
break;
}
//inner switch-case ends
System.out.println("\n\n");
break;
case 3:
//View One account
bankAccounts2=(List<BankAccount>)rw.readFromFile();
BankAccount viewOneAccountNum = null;
System.out.println("Enter the account number you want to see:");
viewOneAcc = sc.nextInt();
System.out.println("Name\tAccount No\tInitial Amount");
for (BankAccount viewOneAccountProperty : bankAccounts2) {
if (viewOneAccountProperty.getAccNum() == viewOneAcc) {
//viewOneAccountNum=viewOneAccountProperty;
viewOneAccountNum = viewOneAccountProperty;
System.out.println(viewOneAccountNum);
}
System.out.println("");
}
break;
case 4:
bankAccounts2=(List<BankAccount>)rw.readFromFile();
//BankAccount AccToDel = null;
//Deleting an account
Iterator<BankAccount> it = bankAccounts2.iterator();
System.out.println("Enter the account you want to delete:");
deleteAcc = sc.nextInt();
while (it.hasNext()) {
BankAccount next = it.next();
if (next.getAccNum() == deleteAcc) {
it.remove();
}
}
rw.writeToFile(bankAccounts2);
break;
case 5:
//View all the accounts/printing them out
bankAccounts2=(List<BankAccount>)rw.readFromFile();
System.out.println("Name\tAccount No\tInitial Amount");
for (BankAccount bankAccount : bankAccounts2) {
System.out.println(bankAccount);
}
System.out.println("\n\n");
break;
case 6:
//Quit
return;
}
//switch-case ends
}
}
}
ReaderWriter:
public class ReaderWriter{
public void writeToFile(List<BankAccount> accounts){
try {
FileOutputStream fos=new FileOutputStream("C:\\Users\\Documents\\NetBeansProjects\\BankFile_assignment.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(accounts);//take the arrayList
oos.flush();
oos.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public List<BankAccount> readFromFile(){
List<BankAccount>readData=null;
try {
FileInputStream fis=new FileInputStream("C:\\Users\Documents\\NetBeansProjects\\BankFile_assignment.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
//make an arrayList to get those object back
//arrayList
readData=(List<BankAccount>)ois.readObject();
ois.close();
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
//return readData;
return readData;
}
}
BankAccount:
package bankapp_assignment;
import java.io.Serializable;
public class BankAccount implements Serializable{
private String name;
private int accNum;
private double initiateAmount;
//constructor
public BankAccount() {
this.name = null;
this.accNum = 0;
this.initiateAmount = 0;
}
public void setName(String name) {
this.name = name;
}
public void setAccNum(int accNum) {
this.accNum = accNum;
}
public String getName(String name){
return name;
}
public int getAccNum() {
return accNum;
}
public void setInitiateAmount(double initiateAmount) {
this.initiateAmount = initiateAmount;
}
public double getInitialAmount(){
return initiateAmount;
}
#Override
public String toString() {
return name + "\t\t" + accNum + "\t\t" + initiateAmount;
}
}
you should refactor whole main method. If I were you, I would use
main only to lunch program, rest process in other methods. This way you would be able to use class fields all over program, and divide code into many methods.
You should divide main beetween other methods, to at least method
per action, exemple:
case 1:
createAccount();
break;
(...)
public void createAccount(){
code from your swich case 1
}
etc. You can still use swich control, but should replece logic code to another method.
When i run your code, input/output didn't work. Were you able to
save/load file? I had to chage:
File file = new File("//file path");
FileOutputStream fos = new FileOutputStream(file);
ObjectOutput oos = new ObjectOutputStream(fos);
Same with input. Then it worked.
Now, we will try to deal with operation on BankAccounts from files. I change a little bit your code from case2/case2: deposit/withdraw, lets look at it:
bankAccounts2 = rw.readFromFile(); // loading list from file
BankAccount edited = new BankAccount(); // creating new object
System.out.println("Enter the account number you want to deposit or withdraw from:");
double input = sc.nextInt(); // you don't need to create new variable every time you take input form user
for(BankAccount account : bankAccounts2){ // every account in list
if(account.getAccNum() == input) edited = account; // if acccNum match, give edited reference to chosen account
}
System.out.println("Enter the amount (To withdraw enter a negative value)");
input = sc.nextDouble();
double result = edited.getInitialAmount() + input; // result of operation
if(result < 0){ // check if there is enough money on account
System.out.println("Withdraw amount is bigger than the current amount.\nChoose the menu again. .");
break;
}else{
edited.setInitiateAmount(result); // if there is, set new value
}
rw.writeToFile(bankAccounts2); // save file
You can implement another operation in similar style. But still, you should consider dividing main into other methods, adding class fields, etc.
EDIT:
For question in comments.
Because you use positive numbers for deposit, and negative numbers for withdraw, the operation on initialAmount will be always the same: initialAmount + input (if negative, is will subtract from amount), so you can treat it like an one case in your code. In your code you use this line twice:
fromAcc_SameAcc.setInitiateAmount(fromAcc_SameAcc.getInitialAmount() + depOrWithAmount);
so you already could merge both cases into one, to avoid unnecessary repetitions. So only case when action will differ, is when there is not enough money on a account, you check it by:
if (depOrWithAmount - 1 < fromAcc_SameAcc.getInitialAmount())
but i think i will not work, because in withdraw operation depOrWithAmount is in negative numbers, so it will always be smaller than fromAcc_SameAcc.getInitialAmount(). You can use:
if (depOrWithAmount < 1 - fromAcc_SameAcc.getInitialAmount())
(but i think it is not too readable) or:
if (Math.abs(depOrWithAmount) > fromAcc_SameAcc.getInitialAmount()){}
to compare absolute value of input with initialAmout. However i used:
double result = edited.getInitialAmount() + input;
if(result < 0){...}
because it gives me result variable, which I can reuse if there is enough money, to gives new value to initialAmount. And if result is negative, it means that withdraw amount was bigger than initialAmount, so ther is no enough monay to withdraw.
I hope you found something useful in my post.
I'm writing a simple Java program, to familiarise myself with methods, that logs the people a person has met. For instance, if I meet Alison in London, I would log the following (Format: name,gender,when,where):
Alison,F,apr2013,London
The program is built up as follows:
The user is presented with different opportunities:
Log person
Search for all people named [name]
Search for all people met [place]
Get a list of available commands
Quit
Here is the skeleton of my code:
public void chooseCommand() throws FileNotFoundException {
System.out.println("Enter command: ");
text = input.next();
myCommand = Integer.parseInt(text);
while (myCommand !=5) {
if (myCommand == 1) {
writeToFile(); //Log new person
}
// Search for person type
else if (myCommand == 2) {
searchFor(); // Search for person by name
}
// Search for place
else if (myCommand == 3) {
searchFor(); // Search for person by place
}
// help
else if (myCommand == 4) {
showCommands(); // get a list of available commands
}
else if (myCommand == 5) {
exit();
}
// default
else {
System.out.println("Command not found");
}
}
}
This works just fine. However, after I choose one of the five options (log new person, search for name, search for place, help, quit), I would like to go back to the chooseCommand() method, so as to get the same options presented again, instead of having the initially chosen method loop infinitely. That is to say, after I log a new person, I want to be able to get new options, as opposed to having to log new people for all eternity, without killing the program.
// REGISTER
public void writeToFile() {
// Write to file
try {
BufferedWriter output = new BufferedWriter(new FileWriter(file, true));
System.out.println("Enter sighting: ");
for (int i = 0; i < personBlank.length; i++) {
System.out.println(personInfo[i] + ": ");
personEntry = input.next();
personBlank[i] = personEntry;
}
// change to toString() method
observed = personBlank[0] + "," + personBlank[1] + "," + personBlank[2] + "," + personBlank[3];
if (observed.equals(escape)) {
exit();
}
else {
output.write(observed); // log new person
output.newLine();
output.close();
}
back();
}
catch (IOException e){
e.printStackTrace();
}
}
Any help on this is highly appreciated!
public void someMethod() {
while(isRunning) {
chooseCommand();
}
}
Then in chooseCommand() lose the loop, make option 5 set isRunning = false instead of exit(), and use a switch statement for prettyness.
e.g.
public void chooseCommand() throws FileNotFoundException {
System.out.println("Enter command: ");
text = input.next();
myCommand = Integer.parseInt(text);
switch (myCommand) {
case 1:
writeToFile(); //Log new person
break;
case 2:
// Search for place
break;
case 3:
searchFor(); // Search for person by place
break;
// help
case 4:
showCommands(); // get a list of available commands
break;
case 5:
this.isRunning = false;
break;
default:
System.out.println("Command not found");
}
}
in the place of your code where chooseCommand() was called you could use a boolean and check that boolean is true to call chooseCommand()
java pseudocode
------------------
boolean continue=true;
while(continue)
{
System.out.println("Do you want to continue?");
Scanner scan=new Scanner(System.in);
if(scan.nextLine().equals("true"))
chooseCommand();
else
continue = false;
}