JOptionPane not displaying and code doesn't proceed - java

I have been trying to build a simple java application which simulates bank deposits and withdrawals.
I tried to use the JOptionPane to show an error if the user tries to withdraw more than the bank account balance. But the JOptionPane does not display the message and the code does not proceed to the next line.
My Bank class which contains the main application
import java.util.Scanner;
public class Bank {
public static void main(String[] args)
{
//Define an object of type Scanner to get the input
Scanner inp = new Scanner(System.in);
String name; //Local variable to get the name
double bal; //Local variable to get the balance
//Getting the inputs from the user
System.out.println("Enter the name: ");
name = inp.nextLine();
System.out.println("Enter the balance: ");
bal = inp.nextDouble();
Account a1 = new Account(name, bal); //Creating Account object a1
inp.nextLine();
/**The above command is to remove the newline character after
inp.nextDouble() since it is not consumed by it and this affects
the string input in the following lines*/
System.out.println("Enter the name: ");
name = inp.nextLine();
System.out.println("Enter the balance: ");
bal = inp.nextDouble();
Account a2 = new Account(name, bal); //Creating Account object a2
//Displaying the input details
a1.dispDetails();
a2.dispDetails();
/**For this app we just withdraw money from a1 and deposit in a2 */
System.out.println("Enter the amount to be withdrawn from a1");
double w_d = inp.nextDouble();
a1.withdraw(w_d);
a1.dispDetails();
System.out.println("Enter the amount to be deposited in a2: ");
double deposit = inp.nextDouble();
a2.credit(deposit);
a2.dispDetails();
System.out.println( "Number of accounts created is "+Account.getCount());
}
}
My Account class in which the JOptionPane is not working
import javax.swing.*;
public class Account {
/** Declaration of the class variables*/
private final String name; //store the name of the account holder
private double balance;//store the balance
private final int acc_num; //since account number is not changed, set as final
static int count = 0; //to keep track of the number of accounts
JFrame f = new JFrame();
public Account(String n,double bal)
{
count++;
this.name = n;
//generating a random account number based on count
this.acc_num = count*599*254715;
this.balance = bal;
}
/** static function to access the static variable*/
static int getCount()
{
return count;
}
/** To deduct amount on withdrawal Raises a warning if there is
insufficient balance*/
public void withdraw (double amt)
{
if(amt < balance)
balance -= amt;
else
{
JOptionPane.showMessageDialog(f, "Insufficient Balance");//not working
}
}
//credit an amount to the account
public void credit (double amt)
{
balance += amt;
}
//display the details of the account
public void dispDetails()
{
System.out.println("Name: "+name+"\nAccount number: "+acc_num);
System.out.println("Balance= "+balance+"\n");
}
}
It does not get any input or stop running after the JOptionPane line.
Please help. Thanks

I think it has something to do with the AWT-Thread and how the shutdown happens (it needs at least one active window it seems). I fixed it by creating an invisible JFrame which somehow doesn't let the AWT-Threads end. Just put this as the first statements in your main:
JFrame f = new JFrame();
f.setVisible(true);
SwingUtilities.invokeLater(() -> f.setVisible(false));
and your JOptionPane will work.

Related

How do i pass a specific content of an index of an arraylist to a method?

How do i pass a specific content of an index of an arraylist to a method? (i'm not sure of the correct terms)
This is what i'm trying to achieve:
Get user input for the amount to withdraw from the first account, then print the balance. Repeat
the same for deposit.
This is my class code:
import java.util.Date;
public class Account2 {
private int id = 0;
private double balance = 0;
private static double annualInterestRate = 0;
private Date dateCreated;
public Account2() {
id = 0;
balance = 0;
}
public Account2(int id, double balance) {
this.id = id;
this.balance = balance;
}
// getters and setters (omitted for brevity)
public double withdraw(int amount) {
return balance - amount;
}
public double deposit(int amount) {
return balance + amount;
}
}
This is the Test class:
import java.util.ArrayList;
import java.util.Scanner;
public class TestAccount2 {
public static void main(String[] args) {
//Account2 acc = new Account2();
Account2.setannualInterestRate(4.5);
//Creates an ArrayList of 3 Account objects
ArrayList<Account2> list = new ArrayList<Account2>();
for(int i=1; i<4; i++) {
//USE ARRAYLIST SYNTAX
list.add(new Account2(i+100, i*10000 ));
}
//print all the content of ArrayList
for(Account2 auto : list) {
System.out.println(temp);
}
System.out.println("Enter the amount you'd like to withdraw: ");
Scanner input = new Scanner(System.in);
double amount = amount.nextDouble;
// Get user input for the amount to withdraw from the first account, then print the balance.
// Repeat the same for deposit
}
}
This is where i'm stuck:
System.out.println("Enter the amount you'd like to withdraw: ");
Scanner input = new Scanner(System.in);
double amount = amount.nextDouble;
// Get user input for the amount to withdraw from the first account, then print the balance.
// Repeat the same for deposit
This is the method i'm trying to pass the index of arraylist into:
public double withdraw(int amount) {
return balance - amount;
}
thank u.
You need to invoke those methods specifying the instance of the account you want to alter. For example, if you want to withdraw from the first account of the ArrayList, you'll write something like:
list.get(0).withdraw(amount);
You can do the same for the deposit method.

How to create multiple accounts with user input using class constructor

I have created this bank account class constructor in java that makes it possible to create any number of accounts. This is part of an assignment for my java course. However, I have to manually specify each attribute of the accounts (Account ID, and balance).
What I want to do is get the user involved. For example, the user should be prompted if they want to create a new account. If they answer yes, they should be able to set the account number (weird? I know) and the account balance. The program should then create the account for them using the inputs.
I already have the options for checking account balance, making deposit or withdrawal that is working as expected, however, I want it to work for multiple accounts created. For example, the user is prompted if they want to create new account, and if yes, specify account number and balance. If they want to check the status of existing accounts, the program should give them an option of which account they want to get info about. Then the program should go through the routine behavior of displaying the prompts that I have already created.
It would also be nice if the code lets the user to create multiple accounts at once. For example:
In main, create an array of 10 Account objects with id 0 - 9 and starting balance of $100 each.
Prompt the user for an id.
Prompt the user for an amount to withdraw or deposit (or both).
Modify that Account, then print its balance.
Here is my existing class constructor portion:
// Bank account class creator
public class Account {
// Create attributes for the Account class
private int id;
private double balance;
private double withdraw;
private double deposit;
private static double annualRate;
private static String dateCreated;
// Create default constructor
Account() {
id = 0;
balance = 0;
java.util.Date date = new java.util.Date();
dateCreated = date.toString();
annualRate = 4.5;
}
// Create constructor which allows input values
Account(int accountId, double accountBalance) {
this.id = accountId;
this.balance = accountBalance;
}
// Getter for account ID
int getId() {
return this.id;
}
// Getter for account balance
double getBalance() {
return this.balance;
}
// Getter for annual interest rate
double getAnnualRate() {
return this.annualRate;
}
// Getter for date
String getDate() {
return this.dateCreated;
}
// Getter for monthly interest amount
double getMonthlyInterest() {
return this.balance * this.annualRate / 1200;
}
// Getter for annual interest amount
double getAnnualInterest() {
return this.balance * this.annualRate / 100;
}
// Validate deposit (filter negative numbers out)
double deposit(double depositAmount) {
if (depositAmount > 0) {
this.balance = this.balance + depositAmount;
return this.balance;
}
else return 0;
}
// Validate withdraw (filter negative numbers out)
double withdraw(double withdrawAmount) {
if (withdrawAmount > 0) {
this.balance = this.balance - withdrawAmount;
return this.balance;
}
else return 0;
}
// Validate ID (filter negative numbers out)
void setId(int accountId) {
if (accountId > 0)
this.id = accountId;
else
this.id = 0;
}
// Validate interest rate (filter negative numbers out)
void setAnnualRate(double currentInterest) {
if (currentInterest > 0)
this.annualRate = currentInterest;
else
this.annualRate = 0;
}
// Setter for balance
void setBalance() {
this.balance = this.balance + this.deposit - this.withdraw;
}
}
Here is the main code that uses the constructor to create accounts:
// Bank account tester
import java.util.Scanner; // import java Scanner utility
public class TestAccount {
public static void main(String[] args) {
Account account1 = new Account(); // Create a new account
Scanner input = new Scanner(System.in); // Create a Scanner object
System.out.println("1. Show balance");
System.out.println("2. Deposit funds");
System.out.println("3. Withdraw funds");
System.out.println("4. Exit");
System.out.println("");
System.out.print("Enter choice: ");
int userInput = input.nextInt(); // Get input from the user
while (userInput != 4) { // Start of loop to check for exit condition
if(userInput == 1) {
// Display account balance, monthly interest and current date
System.out.printf("Balance: $%.2f\n" , account1.getBalance());
System.out.printf("Monthly interest $%.2f\n" , account1.getMonthlyInterest());
System.out.println("Date created: " + account1.getDate());
}
else if (userInput == 2) {
// Deposit funds to account
System.out.println("Enter amount to deposit:");
double inputAmount = input.nextDouble();
account1.deposit(inputAmount);
}
else if (userInput == 3) {
// Withdraw funds from account
System.out.println("Enter amount to withdraw:");
double inputAmount = input.nextDouble();
account1.withdraw(inputAmount);
} else
// Prompt the user to input option choice if they input invalid option
System.out.println("That is not a valid choice. Please enter a valid choice; ");
// Continue displaying the options until the user's option is to exit
System.out.println("");
System.out.println("1. Show balance");
System.out.println("2. Deposit funds");
System.out.println("3. Withdraw funds");
System.out.println("4. Exit");
userInput = input.nextInt(); // Continue getting inputs until user chooses to exit
}
input.close(); // close the input method
// Display an exit message when the user chooses to exit
System.out.println("Thank you for using our banking software ");
}
}
I would also appreciate if you could point out to any error or redundancy in my code, for example incorrect use of static or redundant "this." keyword.
Few thing regarding of possible refactoring:
Invalid use of static in Account:
the keyword static indicates that the particular member belongs to a type itself, rather than to an instance of that type.
Blockquote
annualRate and dateCreated should NOT be static as it means that these values will be shared among all instances of Account class.
Its possible to remove duplicated code for print of program options:
private void printHelp() {
System.out.println("1. Show balance");
System.out.println("2. Deposit funds");
System.out.println("3. Withdraw funds");
System.out.println("4. Exit");
}

Java getter setter failing to store value

I'm trying to answer these questions.
The New Account option should implement the following:
Input client details: name, address, birthday, and contact number
Input the initial deposit of not less than PhP5,000
Generate a four-digit account number randomly
The Balance Inquiry option should implement the following:
Input the account number and validate
If the account number is valid, display the client name and current
balance
I've tried coding the New Account option with setter methods in it and also generates a four-digit number randomly that I can use to input it in the Balance Inquiry option that has getter methods but it displays empty. I tried debugging it and the variables return empty after exiting the if statement.
Class with the main method, displayMainMenu() for the options, newAccount() and fourRandomNumber().
public class ClientUgang {
public static void main(String[] args) {
displayMainMenu();
}
public static void displayMainMenu() {
SavingsAccountUgang savingsAccount = new SavingsAccountUgang();
int option = 0;
while (option != 7) {
Scanner scan = new Scanner(System.in);
System.out.println("JBank Main Menu");
System.out.println("[1] New Account");
System.out.println("[2] Balance Inquiry");
System.out.println("[3] Deposit");
System.out.println("[4] Withdraw");
System.out.println("[5] Client Profile");
System.out.println("[6] Close Account");
System.out.println("[7] Exit");
option = scan.nextInt();
if (option == 1) {
newAccount();
}
if (option == 2) {
savingsAccount.balanceInquiry();
}
}
}
public static void newAccount() {
Scanner scan = new Scanner(System.in);
SavingsAccountUgang savingsAccount = new SavingsAccountUgang();
System.out.print("Name: ");
String name = scan.nextLine();
System.out.print("Address: ");
String address = scan.nextLine();
System.out.print("Birthday: ");
String birthday = scan.nextLine();
System.out.print("Contact number: ");
String contactNumber = scan.nextLine();
savingsAccount.setAccountName(name);
savingsAccount.setAddress(address);
savingsAccount.setBirthday(birthday);
savingsAccount.setContactNumber(contactNumber);
int deposit = 0;
while (deposit < 5000) {
System.out.print("Initial deposit(not less than Php5000): ");
deposit = scan.nextInt();
}
savingsAccount.setBalance(deposit);
int fourDigitNumber = fourRandomNumber(1000, 9000);
savingsAccount.setAccountNo(fourDigitNumber);
System.out.println("Your Account Number: " + fourDigitNumber);
System.out.println();
}
public static int fourRandomNumber(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
}
The Class where my balanceInquiry() method is. My setter and getter method for accountName is in BankAccountUgang class.
public class SavingsAccountUgang extends BankAccountUgang {
private int accountNo;
private double balance;
public SavingsAccountUgang() {
}
public int getAccountNo() {
return accountNo;
}
public void setAccountNo(int accountNo) {
this.accountNo = accountNo;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public void balanceInquiry() {
Scanner scan = new Scanner(System.in);
int accountNumber = 0;
do {
System.out.print("Enter Account Number: ");
accountNumber = scan.nextInt());
} while (accountNumber != getAccountNo());
System.out.println(getAccountName());
System.out.println(getBalance());
System.out.println();
}
}
I expect the setter methods to work so that I can call the getter methods.
JBank Main Menu
[1] New Account
[2] Balance Inquiry
[3] Deposit
[4] Withdraw
[5] Client Profile
[6] Close Account
[7] Exit
1
Name: John
Address: World
Birthday: Aug 2019
Contact number: 123 1234
Initial deposit(not less than Php5000): 5000
Your Account Number: 6810
JBank Main Menu
[1] New Account
[2] Balance Inquiry
[3] Deposit
[4] Withdraw
[5] Client Profile
[6] Close Account
[7] Exit
2
Enter Account Number: 6810
Enter Account Number: BUILD STOPPED (total time: 27 seconds)
There are a lot of issues with your code.
To fix that 1 way is below:
Return a new saving account from the newAccount method, so change the return type to:
public static SavingsAccountUgang newAccount() {
// Your existing code
return savingsAccount;
}
Then in your displayMainMenu() method save this account if the user enters 1 as an input and later use that instance to show the balance:
public static void displayMainMenu() {
SavingsAccountUgang savingsAccount = null // don't create object here as you are doing
// Your code
if (option == 1) {
savingsAccount = newAccount();
}
if (option == 2) {
if(savingsAccount == null) {
// throw exception or whatever you want to do.
}
savingsAccount.balanceInquiry();
}
}
The SavingsAccountUgang instance in your newAccount() method is a local variable and therefore only visible to this method.
If you want to use it outside your method you have to return or declare it outside of your method.
Well, the setBalance() method requires an argument type double, but you send a type int, but it's not a reason for a mistake. Also, you should use this in a statement like this one:
while (accountNumber != this.getAccountNo());

bank account client in java with multiple classes

I am trying to make a bank account program, but I cannot figure out how to get all my variables visible to every class that I have, or how to make the withdrawal and deposit methods of my code visible. Can anyone look at my code and tell me what is wrong? I only want input and output in the client class.
Thanks
Client Class
public class Client {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your Name: ");
String cusName = input.nextLine();
System.out.println("Enter Account Type: ");
String type = input.next();
System.out.println("Enter Initial Balance: ");
int bal = input.nextInt();
BankAccount b1 = new BankAccount(cusName, num, type, bal);
int menu;
System.out.println("Menu");
System.out.println("1. Deposit Amount");
System.out.println("2. Withdraw Amount");
System.out.println("3. Display Information");
System.out.println("4. Exit");
boolean quit = false;
do {
System.out.print("Please enter your choice: ");
menu = input.nextInt();
switch (menu) {
case 1:
b1.deposit();
break;
case 2:
b1.withdraw();
System.out.println("Current Account Balance=" + Balance);
System.out.print("Enter withdrawal amount:");
amount = input.nextInt();
break;
case 3:
b1.display();
break;
case 4:
quit = true;
break;
}
} while (!quit);
}
}
Money Class
public class Money
{
static int accountNumber, Balance, amount;
Scanner input = new Scanner(System.in);
static String name, actype;
public int deposit() {
System.out.print("Enter depost amount:");
amount = input.nextInt();
if (amount < 0) {
System.out.println("Invalid");
return 1;
}
Balance = Balance + amount;
return 0;
}
int withdraw() {
if (Balance < amount) {
System.out.println("Not enough funds.");
return 1;
}
if (amount < 0) {
System.out.println("Invalid");
return 1;
}
Balance = Balance - amount;
return 0;
}
}
BankAccount Class
class BankAccount {
Scanner input = new Scanner(System.in);
static String name, actype;
static int bal, amt;
Random randomGenerator = new Random();
int accNo = randomGenerator.nextInt(100);
BankAccount(String name, int accNo, String actype, int bal) {
this.name = name;
this.accNo = accNo;
this.actype = actype;
this.bal = bal;
}
void display() {
System.out.println("Name:" + name);
System.out.println("Account No:" + accNo);
System.out.println("Balance:" + bal);
}
void dbal() {
System.out.println("Balance:" + bal);
}
}
Add Money to your BankAccount and create a getter method as:
class BankAccount {
Scanner input = new Scanner(System.in);
static String name, actype;
static int bal, amt;
Random randomGenerator = new Random();
int accNo = randomGenerator.nextInt(100);
Money money;
BankAccount(String name, int accNo, String actype, int bal) {
this.name = name;
this.accNo = accNo;
this.actype = actype;
this.bal = bal;
this.money = new Money();
}
public Money getMoney(){
return this.money;
}
.....
}
Use bankaccount.getMoney() to invoke deposit and withdraw as :
b1.getMoney().deposit();
b1.getMoney().withdraw();
In addition, I would advice to make the Money class attributes e.g. amount, accntType... non-static and set through through a constructor. Static variables are associated with class definition and hence you won't be abl to maintain them per Bank Account.
I'm not going to answer this question for you. Instead, I'm going to recommend that you read a bit more about Java programming concepts that will explain it to you, by default.
Here is one on encapsulation, which is the main concept that you're asking about
This is a great book on how to write code well, including things like keeping methods short
In particular, your main method should be broken into smaller pieces
Here's a stack overflow question that talks about it if you don't want to buy the book.
If you don't want to read any of these links, #YogendraSingh answered this question really well, use that answer.
Attributes to an object shouldn't be static, for example your "name, actype, bal and amt". Also I think your money class should exist and those methods could be in a bank account (you deposit/withdraw from a bank account).

Bank Account Program Issue

For my Java class, we need to make a bank account that has the methods of withdrawing, depositing money, and displaying current balance. In the Tester class, I want to make it ask for the name, the balance, then allow you to choose 1, 2, or 3. Then it repeats the option you choose until you say type "n". The problem is that running this code causes it to say after you deposit money "You deposited (amount of money deposited) in the account (name of account). Your new balance is (this)." The part where it says "this" is the exact same of the amount of money deposited. In other words, it doesn't add it, it just makes the new balance the same as the deposit, regardless of how much was in before. Any help? Thanks.
import java.io.*;
import java.util.*;
public class BankAccount
{
public BankAccount(double b, String n)
{
double balance = b;
String name = n;
}
public void deposit(double d)
{
balance += d;
}
public void withdraw(double w)
{
balance -= w;
}
public String nickname()
{
System.out.print("Enter a new name: ");
Scanner kbIn = new Scanner(System.in);
String n = kbIn.nextLine();
return n;
}
double balance;
String name;
}
And the tester class:
import java.io.*;
import java.util.*;
public class Tester
{
public static void main(String args[])
{
Scanner kbInLine = new Scanner(System.in);
Scanner kbIn = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = kbInLine.nextLine();
System.out.print("Please enter balance: $");
double balance = kbIn.nextDouble();
BankAccount myAccount = new BankAccount(balance, name);
String proceed = "y";
while(proceed.equalsIgnoreCase("y"))
{
System.out.println("\nPlease pick a number. Would you like to...\n\t 1. Deposit\n\t 2. Withdraw\n\t 3. Print Balance\n");
int choice = kbIn.nextInt();
switch(choice)
{
case 1:
System.out.print("How much would you like to deposit?\n\t$");
double deposit = kbIn.nextDouble();
myAccount.deposit(deposit);
System.out.println("You have deposited $" + deposit + " into the account of " + name + ". The new balance is: " + myAccount.balance);
break;
case 2:
System.out.print("How much would you like to withdraw?\n\t$");
double withdraw = kbIn.nextDouble();
if(myAccount.balance - withdraw > 0)
{
myAccount.withdraw(withdraw);
System.out.println("You have withdrawn $" + withdraw + " from the account of " + name + ". The new balance is: " + myAccount.balance);
}
else
{
System.out.println("Sorry, you have insufficient funds for this operation. Your existing balance is $" + myAccount.balance);
}
break;
case 3:
System.out.print("The balance in the account of " + name + " is $" + myAccount.balance);
break;
}
System.out.print("\nWould you like to do another transaction? (Y/N)");
proceed = kbIn.next();
}
System.out.println("\nThank you for banking with us. Have a good day!");
}
}
What's really wierd is that I did a project before this one (it's actually a simplified version) where it deposits and then withdraws a predetermined, coded amount, then outputs the new bank balance, and it does it fine. But the code for BankBalance is the same. Here's the code for those.
BankAccount class is:
public class BankAccount
{
public BankAccount(String nm, double amt) // Constructor
{
name = nm;
balance = amt;
}
public void deposit(double d) // Sets up deposit object as balance += d
{
balance += d;
}
public void withdraw(double w) // Sets up withdraw object as balance -= w
{
balance -= w;
}
public double balance;
public String name;
}
And the Tester class is:
import java.io.*;
import java.util.*;
public class Tester
{
public static void main(String args[])
{
Scanner kbIn = new Scanner(System.in);
System.out.print("Enter your name:");
String name = kbIn.nextLine();
System.out.print("Enter the balance:");
double balance = kbIn.nextDouble();
BankAccount myAccount = new BankAccount(name, balance);
myAccount.deposit(505.22);
System.out.println(myAccount.balance);
myAccount.withdraw(100.00);
System.out.println("The " + myAccount.name + " account balance is, $" + myAccount.balance);
}
}
You're not actually initialising your balance member variable here:
public BankAccount(double b, String n)
{
double balance = b;
This creates a new local variable called balance, to which you assign the value of b. The member variable balance will remain 0 (the default) after this constructor is run.
public BankAccount(double b, String n)
{
double balance = b;
String name = n;
}
--->
public BankAccount(double b, String n)
{
this.balance = b;
this.name = n;
}
Or you can declare balance as static (data class field), and the methods that use this variable as static too.

Categories

Resources