Account class Error - java

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.

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

Getting data from main program

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

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

The else if section is not working

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

Java Bank Program has a weird ghost loop?

I cannot figure this problem out. Everything in the program works the way i want it to except after i use the 'o' open account option, 'w' withdrawal accout options.. etc that after completion, repeats the loop as desired, but returns the else line "Command was not recognized; please try again." and then reprints the menu. If i use the 's' command it works fine. i removed the "balance = input.nextDouble();" line and it works correctly, but i can't figure out why it returns the else statement and reprints.
import java.util.Scanner;
import java.text.*;
public class Bank
{
public static void main( String[] args )
{
Scanner input = new Scanner( System.in );
String eol = System.getProperty("line.separator");
DecimalFormat df = new DecimalFormat("0.00");
int numAccounts = 1;
String number = "None Selected";
String userInput;
double balance = 0;
double amount = 0;
int i = 0;
int j;
BankAccount[] accounts = new BankAccount [100];
accounts[0] = new BankAccount (number, balance);
String BBalance = df.format(accounts[i].getBalance());
while (1 < 2){
if (numAccounts == accounts.length){
BankAccount[] tempArray = new BankAccount[accounts.length * 2];
for (int k = 0; k < accounts.length; k++){
tempArray[k] = accounts[k];
}
accounts = tempArray;
}
try{
System.out.print ( eol +
"-----------------------------------------------------" + eol +
"|Commands: o - Open account c - Close account|" + eol +
"| d - Deposit w - Withdraw |" + eol +
"| s - Select account q - Quit |" + eol +
"-----------------------------------------------------" + eol +
"Current account: " + accounts[i].getNumber() + " Balance: $" + df.format(accounts[i].getBalance()) +
eol );
}
catch(java.lang.Throwable t) {
System.out.println("Account number was not found");
}
userInput = input.nextLine().trim().toLowerCase();
if (userInput.substring(0).equals("o")) {
System.out.print("Enter Account Number: ");
number = input.nextLine();
System.out.print("Enter Initial Balance: ");
balance = input.nextDouble();
accounts[numAccounts++] = new BankAccount (number, balance);
i = numAccounts - 1;
continue;
}
else if (userInput.substring(0).equals("d")) {
System.out.print("Enter Account Number: ");
number = input.nextLine();
for (i =0; i < numAccounts; i++)
if (accounts[i].getNumber().equals(number))
break;
System.out.print("Enter Amount To Deposit: ");
amount = input.nextDouble();
accounts[i].deposit(amount);
continue;
}
else if (userInput.substring(0).equals("s")) {
System.out.print("Enter Account Number: ");
number = input.nextLine();
for (i =0; i < numAccounts; i++){
if (accounts[i].getNumber().equals(number)){
break;
}
}
if (i != numAccounts){
System.out.print("Account number was not found");
}
continue;
}
else if (userInput.substring(0).equals("c")) {
System.out.print("Enter Account Number: ");
number = input.nextLine();
for (i =0; i < numAccounts; i++)
if (accounts[i].getNumber().equals(number))
break;
accounts[i] = accounts[--numAccounts];
continue;
}
else if (userInput.substring(0).equals("w")) {
System.out.print("Enter Account Number: ");
number = input.nextLine();
for (i =0; i < numAccounts; i++)
if (accounts[i].getNumber().equals(number))
break;
System.out.print("Enter Amount To Withdraw: ");
amount = input.nextDouble();
accounts[i].withdraw(amount);
continue;
}
else if (userInput.substring(0).equals("q")) {
System.exit(0);
}
else{
System.out.println("Command was not recognized; please try again.");
continue;
}
}
//System.out.print(userInput);
//System.out.print(accounts[0]);
}
}
Here's the BankAccount class:
public class BankAccount {
String number = "123-456";
double balance = 1.00;
public BankAccount(String accountNumber, double initialBalance){
number = accountNumber;
balance = initialBalance;
}
public void deposit (double amount){
balance += amount;
}
public void withdraw (double amount){
balance -= amount;
}
public String getNumber(){
return number;
}
public double getBalance(){
return balance;
}
BankAccount[] accounts = new BankAccount [100];
}
You're not skipping past the end of the lines when you're reading in the second numbers in the commands that require one.
Adding an input.nextLine() to those is one quick way around it (non I/O lines redacted).
// etc.
} else if (userInput.substring(0).equals("d")) {
System.out.print("Enter Account Number: ");
number = input.nextLine();
System.out.print("Enter Amount To Deposit: ");
amount = input.nextDouble();
input.nextLine();
continue;
} // etc.

Categories