The else if section is not working - java

The else if section of deposit is not working and same is the case with else if section of no for updating the balance.
public class BankAccount
{
static double Balance;
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("enter the account holder's name...");
String Name = sc.next();
System.out.println("enter his account number...");
long AccNo = sc.nextLong();
System.out.println("enter his type of account...");
String AccTyp = sc.next();
System.out.println("enter his current balance...");
Balance = sc.nextDouble();
System.out.println("Do you want to update your balance, press y for yes and n for no...");
if(sc.next().equalsIgnoreCase("y") == true)
{
System.out.println("To withdraw money press w, To deposite the same, press d");
if(sc.next().equalsIgnoreCase("w") == true)
{
System.out.println("Enter the amount the account holder withdrawed");
double withdraw = sc.nextDouble();
double Bal = Withdraw(withdraw);
System.out.println("Account holder " +Name+ " with account number " +AccNo+ " and account type " +AccTyp+ " has the new balance = "+Bal);
}
else if(sc.next().equalsIgnoreCase("d") == true)
{
System.out.println("Enter the amount the account holder deposited");
double deposit = sc.nextDouble();
double Bal = Deposit(deposit);
System.out.println("Account holder " +Name+ " with account number " +AccNo+ " and account type " +AccTyp+ " has the new balance = "+Bal);
}
else
System.out.println("Thank you for your transaction");
}
else if(sc.next().equalsIgnoreCase("n") == true)
{
System.out.println("Thank you for your transaction");
}
System.out.println("Thank you for your transaction");
}
public static double Withdraw(double a)
{
Balance = Balance - a;
return Balance;
}
public static double Deposit(double b)
{
Balance = Balance + b;
return Balance;
}
}

Don't keep invoking the next() method:
if(sc.next().equalsIgnoreCase("w") == true)
...
else if(sc.next().equalsIgnoreCase("d") == true)
Instead the code should be something like:
String response = sc.next();
if(response.equalsIgnoreCase("w"))
...
else if(response.equalsIgnoreCase("d"))
...

If 'if' block execute sc.next() then 'else' block can't execute sc.next(). Assign the input to a variable action like this.
String action=sc.next();
if(action.equalsIgnoreCase("w") == true)
{
System.out.println("Enter the amount the account holder withdrawed");
double withdraw = sc.nextDouble();
double Bal = Withdraw(withdraw);
System.out.println("Account holder " +Name+ " with account number " +AccNo+ " and account type " +AccTyp+ " has the new balance = "+Bal);
}
else if(action.equalsIgnoreCase("d") == true)
{
System.out.println("Enter the amount the account holder deposited");
double deposit = sc.nextDouble();
double Bal = Deposit(deposit);
System.out.println("Account holder " +Name+ " with account number " +AccNo+ " and account type " +AccTyp+ " has the new balance = "+Bal);
}

Related

How to reset the value of a double, int, float etc after an "Incorrect" input by the user

My question is in relation to my line of code resembling an ATM. The current balance being 10000, What i have written shows a message to the user that if they withdraw over the given balance that it is Insufficient balance. However the balance continues to change thus when Inquiring balance the balance is now < the allowed balance. My question is how should i go about resetting the double value for the balance when the Insufficient balance message is shown to the user?
Here is my code.
import java.util.Scanner;
class app {
public static void main(String[] args)
{
long pin = 2927942074l;
double balance = 10000.0;
int attempts = 3;
System.out.println("Please enter your pin.");
while (attempts > 0) {
Scanner keyboardpin = new Scanner(System.in);
long input = keyboardpin.nextLong();
if (input == pin) {
System.out.println("Correct");
System.out.println("Welcome to your ATM");
while (true) { // Keep printing your options unless "Quit" is chosen
int a = 1;
int b = 2;
int c = 3;
int d = 0;
System.out.println(a + " - Inquire Balance");
System.out.println(b + " - Withdraw");
System.out.println(c + " - Deposit");
System.out.println(d + " - Quit");
System.out.println("Please select what you want to do.");
Scanner menuselect = new Scanner(System.in);
int menuinput = menuselect.nextInt();
if (menuinput == a) {
System.out.println(balance);
continue;
}
if (menuinput == b) {
System.out.println("Please enter a withdrawal amount.");
Scanner withdrawamount = new Scanner(System.in);
double withdrawbalace = withdrawamount.nextDouble();
balance = (balance - withdrawbalace);
if (withdrawbalace > balance)
System.out.println("Insufficient balance");
if (withdrawbalace <= balance)
System.out.println("Youre new balance is " + balance);
}
if (menuinput == c) {
}
if (menuinput == d) {
break;
}
if (attempts == 0) {
System.out.println("Maximum number of attempts exceeded");
}
}
} else {
System.out.println("Wrong");
attempts--;
System.out.println("You have " + attempts + " attempts remaining.");
}
}
}
}
Just check whether the user has enough balance before subtracting the amount.
if (menuinput == b) {
System.out.println("Please enter a withdrawal amount.");
Scanner withdrawamount = new Scanner(System.in);
double withdrawbalace = withdrawamount.nextDouble();
if (withdrawbalace > balance)
System.out.println("Insufficient balance");
if (withdrawbalace <= balance)
balance = (balance - withdrawbalace);
System.out.println("Youre new balance is " + balance);
}
Your main problem has been solved in the previous answer, but your code logic has some errors. I have fixed it for you.
import java.util.Scanner;
class app {
public static void main(String[] args) {
final long pin = 2927942074L;
double balance = 10000.0;
int attempts = 3;
System.out.println("Please enter your pin.");
Scanner keyboard = new Scanner(System.in);
while (attempts > 0) {
long input = keyboard.nextLong();
if (input == pin) {
System.out.println("Correct");
System.out.println("Welcome to your ATM");
// Keep printing your options unless "Quit" is chosen
while (true) {
int a = 1;
int b = 2;
int c = 3;
int d = 0;
System.out.println(a + " - Inquire Balance");
System.out.println(b + " - Withdraw");
System.out.println(c + " - Deposit");
System.out.println(d + " - Quit");
System.out.println("Please select what you want to do.");
int menuInput = keyboard.nextInt();
if (menuInput == a) {
System.out.println(balance);
} else if (menuInput == b) {
System.out.println("Please enter a withdrawal amount.");
double withdrawBalance = keyboard.nextDouble();
if (balance >= withdrawBalance) {
balance -= withdrawBalance;
System.out.println("Your new balance is " + balance);
} else System.out.println("Insufficient balance");
} else if (menuInput == c) {
// Deposit code here
} else if (menuInput == d) break;
}
} else {
attempts--;
if (attempts == 0) {
System.out.println("Maximum number of attempts exceeded");
break;
}
System.out.println("Wrong");
System.out.println("You have " + attempts + " attempts remaining.");
}
}
keyboard.close();
}
}
And here are some tips...
Try to choose meaningful variable names.
If the variable has a constant value make it final
If the variable name consists of two, or more, words capitalize the first letter of the second word (eg. menuInput)
If you check the same condition for different cases you can use switch or if, else if, else
Never forget to close the objects you used to release memory
Good Luck

Using Linked List as the output?

I'm trying to write a bank account that asks the user if they want to see records, remove records, and other stuff. This is what I'm trying to produce
My program is nearly done the only problem I'm having is getting the output. I'm getting some weird error when i tried producing the output. When the output works. I'll put it inside a linked list.
public class Bank
{
public static void main(String args[]){
ArrayList<Customer> accounts = new ArrayList<Customer>();
Customer customer1 = new Customer(1, "Savings", "Dollars", 800);
Customer customer2 = new Customer(2, "Checking", "Euro", 1900);
Customer customer3 = new Customer(3, "Checking", "Pound", 8000);
accounts.add(customer1);
accounts.add(customer2);
accounts.add(customer3);
int customerID=4;
String choice;
int deposit;
int withdraw;
Scanner in = new Scanner(System.in);
Customer operation = new Customer();
boolean flag = true;
String accountType;
String currencyType;
int balance;
while(flag){
System.out.println("Select a choice:");
System.out.println("1. Existing customer");
System.out.println("2. New customer");
System.out.println("3. Quit");
String input = in.next();
//existing user
if(input.equals("1")){
System.out.println("Enter CustomerID: ");
customerID = in.nextInt();
System.out.println("Would you like to: ");
System.out.println("1. Deposit ");
System.out.println("2. Withdraw ");
System.out.println("3. Display account info ");
System.out.println("4. Check balance ");
choice = in.next();
if(choice.equals("1")){
System.out.println("How much would you like to deposit?");
deposit = in.nextInt();
operation.deposit(deposit);
}
else if (choice.equals("2")){
System.out.println("How much would you like to withdraw?");
withdraw = in.nextInt();
operation.withdraw(withdraw);
}
else if (choice.equals("3")){
operation.display(accounts.get(customerID));
}
else if (choice.equals("4"))
operation.balance(accounts.get(customerID));
else
System.out.println("Invalid");
}
//new user
else if(input.equals("2")){
//add new user to arraylist
int newID = customerID + 1;
System.out.println("Enter account type: ");
accountType = in.next();
System.out.println("Enter currency type: ");
currencyType = in.next();
System.out.println("Enter initial balance: ");
balance = in.nextInt();
System.out.println("Your customer ID will be: " + newID);
accounts.add(new Customer(newID, accountType, currencyType, balance));
}
else if(input.equals("3")){
System.out.println("Thanks for using this bank!");
flag = false;
}
else{
System.out.println("Invalid");
}
}
}
}
My second class:
public class Customer
{
String accountType, currencyType, info;
public int customerID, balance, amount;
Scanner input = new Scanner(System.in);
public Customer(int customerID, String accountType, String currencyType, int balance)
{
this.accountType = accountType;
this.currencyType = currencyType;
this.customerID = customerID;
this.balance = balance;
this.amount = amount;
}
public Customer() {
// TODO Auto-generated constructor stub
}
public int deposit(int amount){
amount = input.nextInt();
if (amount >= 500) {
System.out.println("Invalid");
}
else{
balance = balance + amount;
}
return balance;
}
public int withdraw(int amount){
if (balance < amount) {
System.out.println("Invalid amount.");
}
else if (amount >= 500) {
System.out.println("Invalid");
}
else {
balance = balance - amount;
}
return balance;
}
public void display(ArrayList<Customer> accounts)
{
System.out.println("CustomerID:" + accounts.customerID);
System.out.println("Account Type:" + accounts.accountType);
System.out.println("Currency Type: " + accounts.currencyType);
System.out.println("Balance:" + accounts.balance);
}
public void balance(ArrayList<Customer> accounts) {
System.out.println("Balance:" + accounts.balance);
}
}
java.util.ArrayList won't have properties or methods such as customerID, accountType, currencyType and balance.
I guess your methods display() and balance() shoudn't take any arguments and should use the properties of the instance to print.
public void display()
{
System.out.println("CustomerID:" + customerID);
System.out.println("Account Type:" + accountType);
System.out.println("Currency Type: " + currencyType);
System.out.println("Balance:" + balance);
}
public void balance() {
System.out.println("Balance:" + balance);
}
Then, these lines
operation.display(accounts.get(customerID));
operation.balance(accounts.get(customerID));
should be
accounts.get(customerID).display();
accounts.get(customerID).balance();
There seems many more things to be corrected -- for example, usage of withdraw().

Account class Error

I am getting an error on this program for some reason and I have no idea what it means. I tried googling around, but nothing related to my issue is coming up. Does this have to do with an IOException by any chance? Also, where does the input get stored? In the class file? For example: if I was to input money into the account, would the inputed value be saved in a different file, or does the fact that I made an array of 30 account for a double amount of all 30 objects created?
Main class:
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];
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;
}
}
}
}
Second Class:
import java.text.NumberFormat; //links to Part2
public class Account
{
private final double RATE = 0.03; //Interest is 3%
private long acctNumber;
private double balance;
private String name;
//Defines owner, account number, and initial balance.
public Account(String owner, long 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);
}
}
Error message:
Enter your account number (1-30):
5
Enter W for withdrawl; D for deposit; X to escape
d
Enter amount to deposit:
50
Exception in thread "main" java.lang.NullPointerException
at Account2.main(Account2.java:40)
You're trying to acces an index of acct but the array is empty Account[] acct = new Account[30];
You should first fill the array, try to make the user create an account first.

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

Enrollment System

I am trying to make a project out of what I had learn online.
public static void main(String[]args){
int balance, payment;
balance = 11310;
String new1 = "new";
String old = "old";
String partial = "partial";
String full = "full";
String no = "no";
String yes = "yes";
String First = "first year second sem";
String Second = "second year first sem";
String Third = "second year second sem";
System.out.print("\nEnter Name: ");
Scanner st = new Scanner(System.in);
String name = st.nextLine();
System.out.print("\nOld Student or New Student: ");
String student = st.nextLine();
if(student.equalsIgnoreCase(new1)){
System.out.print("\nGreetings, "+name);
System.out.print("\nPlease fill out our Registration Form.");
System.out.print("\nThank you!");
try {
if(Desktop.isDesktopSupported()) {
Desktop.getDesktop().open(new File("C:\\Users\\toshiba-1\\Desktop\\Regform1styr.2ndsem - Copy.docx"));
}
}
catch (IOException ioe) {
ioe.printStackTrace();
}
return;
}
System.out.print("\nGreetings, "+name);
System.out.print("\nWould you want to enroll for a new semester? ");
String enroll = st.nextLine();
if(enroll.equalsIgnoreCase(no))
{
System.out.print("\nThank you!");
return;
}
if(enroll.equalsIgnoreCase(yes))
{
}
System.out.print("\nWhich Semester? ");
String semester = st.nextLine();
if(semester.equalsIgnoreCase(First)) // My error started here.
{
}
else if(semester.equalsIgnoreCase(Second))
{
}
else if(semester.equalsIgnoreCase(Third))
{
}
else
{
System.out.print("\nPlease choose a semester.");
}
System.out.print("\nThe Enrollment fee for this Semester is: "+ balance);
System.out.print("\nChoose your Payment term(Partial/Full): ");
String term = st.nextLine();
if(term.equalsIgnoreCase(partial))
{
System.out.print("\nHow much would you like to pay for this semester: ");
Scanner in = new Scanner(System.in);
payment = in.nextInt();
balance = balance - payment;
System.out.print("\nYour Balance is: SR"+ balance);
if(balance > payment){
System.out.print("\nYou have remaining balance of: SR" + balance);
}else if(balance == payment){
System.out.print("\nYou are already paid");
}
}
}
}
I am having trouble when the user chooses on the three string. I alternatively tried this set of codes.
if(semester.equalsIgnoreCase(First))
{
System.out.print("\nPlease choose a semester.");
}
System.out.print("\nThe Enrollment fee for this Semester is: "+ balance);
System.out.print("\nChoose your Payment term(Partial/Full): ");
String term = st.nextLine();
if(term.equalsIgnoreCase(partial))
{
System.out.print("\nHow much would you like to pay for this semester: ");
Scanner in = new Scanner(System.in);
payment = in.nextInt();
balance = balance - payment;
System.out.print("\nYour Balance is: SR"+ balance);
if(balance > payment){
System.out.print("\nYou have remaining balance of: SR" + balance);
}else if(balance == payment){
System.out.print("\nYou are already paid");
}
else if(semester.equalsIgnoreCase(Second))
{
System.out.print("\nPlease choose a semester.");
}
System.out.print("\nThe Enrollment fee for this Semester is: "+ balance);
System.out.print("\nChoose your Payment term(Partial/Full): ");
String term = st.nextLine();
if(term.equalsIgnoreCase(partial))
{
System.out.print("\nHow much would you like to pay for this semester: ");
Scanner in = new Scanner(System.in);
payment = in.nextInt();
balance = balance - payment;
System.out.print("\nYour Balance is: SR"+ balance);
if(balance > payment){
System.out.print("\nYou have remaining balance of: SR" + balance);
}else if(balance == payment){
System.out.print("\nYou are already paid");
}
else if(semester.equalsIgnoreCase(Third))
{
System.out.print("\nPlease choose a semester.");
}
System.out.print("\nThe Enrollment fee for this Semester is: "+ balance);
System.out.print("\nChoose your Payment term(Partial/Full): ");
String term = st.nextLine();
if(term.equalsIgnoreCase(partial))
{
System.out.print("\nHow much would you like to pay for this semester: ");
Scanner in = new Scanner(System.in);
payment = in.nextInt();
balance = balance - payment;
System.out.print("\nYour Balance is: SR"+ balance);
if(balance > payment){
System.out.print("\nYou have remaining balance of: SR" + balance);
}else if(balance == payment){
System.out.print("\nYou are already paid");
}
else
{
System.out.print("Please choose a semester.");
return;
}
But the results keeps on getting mix up. Please help me.
If you want your code to work, you need to add loop for question:
System.out.print("\nWhich Semester? ");
// changed code!!
while(true){
String semester = st.nextLine();
if(semester.equalsIgnoreCase(First)){
break;
}else if(semester.equalsIgnoreCase(Second)){
break;
}else if(semester.equalsIgnoreCase(Third)){
break;
}else{
System.out.print("\nPlease choose a semester.");
}
}
//end of chaged code!!
System.out.print("\nThe Enrollment fee for this Semester is: "+ balance);
However this is really bad idea to base program flow control on Strings like yours.

Categories