How to read and store inputs properly in this program? [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 3 years ago.
How to get input values properly and store them to use further in this program?
I don't know why but this program is outputting Full Name: and Address: at once and taking input values only for Address:. Also, when I'm outputting New Account option, it is not outputting First Name:.
package com.company;
import java.util.Scanner;
public class Main {
public static final Scanner input = new Scanner(System.in);
public String name;
public int age;
public long personummer;
public String address;
public long phoneNumber;
public long amount;
public boolean created = false;
public static void main(String[] args) {
Main BankID = new Main();
int option;
do {
System.out.println("- - - - Welcome to Bank of Hkr - - - -");
System.out.println();
System.out.println("1) New account");
System.out.println("2) View account");
System.out.println("3) Deposit");
System.out.println("4) Withdraw");
System.out.println("5) Exit");
System.out.println();
System.out.println("- - - - - - - - - - - - - - - - - - - - - ");
System.out.println();
System.out.println(">> Please choose an option...");
option = input.nextInt();
switch (option) {
case 1:
BankID.newAccount();
break;
case 2:
BankID.viewAccount();
break;
case 3:
BankID.deposit();
break;
case 4:
BankID.withdraw();
break;
default:
System.out.println(">> Not A Valid Option ");
}
} while (option != 5);
}
public void newAccount() {
System.out.println("New Account Wizard");
System.out.println("------------------");
System.out.println("Enter the following details: ");
System.out.println();
System.out.println("Full Name: ");
name = input.nextLine();
System.out.println("Address: ");
address = input.nextLine();
System.out.println("Age: ");
age = input.nextInt();
System.out.println("Personummer: ");
personummer = input.nextLong();
System.out.print("Phone Number: ");
phoneNumber = input.nextLong();
System.out.println("Thanks. Your details have been saved.");
}
public void viewAccount() {
if (created) {
System.out.println("View Account");
System.out.println("Full Name: " + name);
System.out.println("Age: " + age);
System.out.println("Personummer: " + personummer);
System.out.println("Address: " + address);
System.out.println("Phone Number: " + phoneNumber);
System.out.println("Amount: " + amount);
} else System.out.println("First create an account");
}
public void deposit() {
if (created) {
System.out.println("Deposit");
System.out.print("Enter the deposit amount: ");
amount += input.nextLong();
} else System.out.println("First create an account");
}
public void withdraw() {
if (created) {
System.out.println("Withdraw");
System.out.print("Enter the withdrawal amount: ");
amount -= input.nextLong();
} else System.out.println("First create an account");
}
}
Apologies if the rest of the code isn't related to the question asked. But I'm no expert and might have made some other major mistake in any other part of the code.

I did not go through all the code but I made some changes to address the issues the mentioned. You will see that I am using a separate Scanner for Strings. Also, I am setting created to true once the account has been created. I also added the case for option 5 for completeness.
import java.util.Scanner;
public class Main {
public static final Scanner input = new Scanner(System.in);
public static final Scanner stringInput = new Scanner(System.in);
public String name;
public int age;
public long personummer;
public String address;
public long phoneNumber;
public long amount;
public boolean created = false;
public static void main(String[] args) {
Main BankID = new Main();
int option;
do {
System.out.println("- - - - Welcome to Bank of Hkr - - - -");
System.out.println();
System.out.println("1) New account");
System.out.println("2) View account");
System.out.println("3) Deposit");
System.out.println("4) Withdraw");
System.out.println("5) Exit");
System.out.println();
System.out.println("- - - - - - - - - - - - - - - - - - - - - ");
System.out.println();
System.out.println(">> Please choose an option...");
option = input.nextInt();
switch (option) {
case 1:
BankID.newAccount();
break;
case 2:
BankID.viewAccount();
break;
case 3:
BankID.deposit();
break;
case 4:
BankID.withdraw();
break;
case 5:
break;
default:
System.out.println(">> Not A Valid Option ");
}
} while (option != 5);
}
public void newAccount() {
System.out.println("New Account Wizard");
System.out.println("------------------");
System.out.println("Enter the following details: ");
System.out.println();
System.out.println("Full Name: ");
name = stringInput.nextLine();
System.out.println("Address: ");
address = stringInput.nextLine();
System.out.println("Age: ");
age = input.nextInt();
System.out.print("Personummer: ");
personummer = input.nextLong();
System.out.print("Phone Number: ");
phoneNumber = input.nextLong();
created = true;
System.out.println("Thanks. Your details have been saved.");
}
public void viewAccount() {
if (created) {
System.out.println("View Account");
System.out.println("Full Name: " + name);
System.out.println("Address: " + address);
System.out.println("Age: " + age);
System.out.println("Personummer: " + personummer);
System.out.println("Phone Number: " + phoneNumber);
System.out.println("Amount: " + amount);
} else System.out.println("First create an account");
}
public void deposit() {
if (created) {
System.out.println("Deposit");
System.out.print("Enter the deposit amount: ");
amount += input.nextLong();
} else System.out.println("First create an account");
}
public void withdraw() {
if (created) {
System.out.println("Withdraw");
System.out.print("Enter the withdrawal amount: ");
amount -= input.nextLong();
} else System.out.println("First create an account");
}
}

Related

bank program not working as expected

I know that it is not a debugger site but I just wanted to ask what I am doing wrong in this piece of code.
When I run the program I first add a new account, then when I deposit or withdraw it says Wrong Password. Here is my code
Code :
import java.io.*;
import java.util.Random;
public class BankA {
public static int NewRandom(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public static void main(String args[])throws IOException, InterruptedException {
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);
Bank myBank = new Bank();
int Option = 1, Account_Number, Account_Password, atempts = 0, Pass;
String Name;
double Balance, Money;
System.out.println("Please wait, the system is starting...");
while(Option !=5) {
Thread.sleep(4000);
System.out.println("1) Open a new bank account");
Thread.sleep(250);
System.out.println("2) Deposit to a bank account");
Thread.sleep(250);
System.out.println("3) Withdraw to bank account");
Thread.sleep(250);
System.out.println("4) Print the detailed account information including last transactions");
Thread.sleep(250);
System.out.println("5) Quit");
System.out.println();
System.out.print(" Enter Option [1-5]: ");
Option = Integer.parseInt(br.readLine());
switch(Option) {
case 1 : System.out.println("Enter a customer name :");
Name = br.readLine();
System.out.println("Enter a opening balance :");
Balance = Double.parseDouble(br.readLine());
Thread.sleep(250);
System.out.println("Creating your account....");
Thread.sleep(500);
System.out.println("Account Has been created\n Account number: " + myBank.AddNewAccount(Name, Balance)[0]+"\nYour password : "+ myBank.AddNewAccount(Name, Balance)[1]);
break;
case 2 : System.out.println("Enter a account number :");
Account_Number = Integer.parseInt(br.readLine());
System.out.println("Enter a account password :");
Account_Password = Integer.parseInt(br.readLine());
System.out.println("Enter a deposit amount :");
Money = Double.parseDouble(br.readLine());
myBank.Deposit(Account_Number, Account_Password, Money);
break;
case 3 : System.out.println("Enter a account number :");
Account_Number = Integer.parseInt(br.readLine());
System.out.println("Enter a account password :");
Account_Password = Integer.parseInt(br.readLine());
System.out.println("Enter a deposit amount :");
Money = Double.parseDouble(br.readLine());
myBank.Withdraw(Account_Number, Account_Password, Money);
break;
case 4 : System.out.println("Enter a account number :");
Account_Number = Integer.parseInt(br.readLine());
System.out.println("Enter a account password :");
Account_Password = Integer.parseInt(br.readLine());
myBank.Transactions(Account_Number, Account_Password);
break;
case 5 : System.out.println("Please Enter your password :");
Pass = Integer.parseInt(br.readLine());
if(Pass == myBank.Password) {
System.out.println(" System shutting down.....");
Option = 5;
break;
}
else {
Thread.sleep(250);
System.out.println("You have enter a wrong password. Please try again");
Option = 0;
}
default: System.out.println("Invalid option. Please try again.");
}
}
}
static class Bank {
private int Password=2684;
private BankAccount[] accounts;
private int numOfAccounts;
public Bank() {
accounts = new BankAccount[100];
numOfAccounts = 0;
}
public int [] AddNewAccount(String Name, Double Balance) {
BankAccount b = new BankAccount(Name, Balance);
accounts[numOfAccounts] = b;
numOfAccounts++;
int Acc = b.getAccountNum()[0];
int Pass = b.getAccountNum()[1];
int[]details = {Acc, Pass};
return details;
}
public void Withdraw(int Account_Number, int pass, double Money) {
for (int i =0; i<numOfAccounts; i++) {
int a = accounts[i].getAccountNum()[0];
int p = accounts[i].getAccountNum()[1];
if (Account_Number == a) {
if( pass == p) {
accounts[i].withdraw(Money);
System.out.println(" Amount withdrawn successfully");
return;
} else {
System.out.println("Wrong Password");
}
}
}
System.out.println(" Account number not found.");
}
public void Deposit(int Account_Number, int pass, double Money) {
for (int i =0; i<numOfAccounts; i++) {
int a = accounts[i].getAccountNum()[0];
int p = accounts[i].getAccountNum()[1];
if (Account_Number == a) {
if( pass == p) {
accounts[i].withdraw(Money);
System.out.println(" Amount deposited successfully");
return;
} else {
System.out.println("Wrong Password");
}
}
}
System.out.println(" Account number not found.");
}
public void Transactions(int Account_Number, int pass) {
for(int i = 0;i<numOfAccounts; i++) {
int a = accounts[i].getAccountNum()[0];
int p = accounts[i].getAccountNum()[1];
if (Account_Number == a ) {
if( pass == p) {
System.out.println(accounts[i].getAccountInfo());
System.out.println(" Last transaction: " + accounts[i].getTransactionInfo(accounts[i].getNumberOfTransactions()-1));
return;
} else {
System.out.println("Wrong Password");
}
}
}
System.out.println("Account number not found.");
}
}
static class BankAccount{
private int User_Password;
private int accountNum;
private String customerName;
private double balance;
private double[] transactions;
private String[] transactionsSummary;
private int numOfTransactions;
private static int noOfAccounts=0;
public String getAccountInfo(){
return " Account number: " + accountNum + "\n Customer Name: " + customerName + "\n Balance:" + balance +"\n";
}
public String getTransactionInfo(int n) {
String transaction = transactionsSummary[n];
return transaction;
}
public BankAccount(String abc, double xyz){
customerName = abc;
balance = xyz;
noOfAccounts ++;
User_Password = NewRandom(1000, 9999);
accountNum = NewRandom(800000000, 999999999);
transactions = new double[100];
transactionsSummary = new String[100];
transactions[0] = balance;
transactionsSummary[0] = "A balance of : Rs" + Double.toString(balance) + " was deposited.";
numOfTransactions = 1;
}
public int [] getAccountNum(){
int account = accountNum;
int Pass = User_Password;
int [] details = {account, Pass};
return details;
}
public int getNumberOfTransactions() {
return numOfTransactions;
}
public void deposit(double amount){
if (amount<=0) {
System.out.println("Amount to be deposited should be positive");
} else {
balance = balance + amount;
transactions[numOfTransactions] = amount;
transactionsSummary[numOfTransactions] = "Rs." + Double.toString(amount) + " was deposited.";
numOfTransactions++;
}
}
public void withdraw(double amount) {
if (amount<=0){
System.out.println("Amount to be withdrawn should be positive");
}
else {
if (balance < amount) {
System.out.println("Insufficient balance");
} else {
balance = balance - amount;
transactions[numOfTransactions] = amount;
transactionsSummary[numOfTransactions] = "Rs." + Double.toString(amount) + " was withdrawn.";
numOfTransactions++;
}
}
}
}
}
You have a problem in your code where you create the new account:
System.out.println("Account Has been created\n Account number: " + myBank.AddNewAccount(Name, Balance)[0]+"\nYour password : "+ myBank.AddNewAccount(Name, Balance)[1]);
You're calling myBank.AddNewAccount() twice on that line, which means that the account number printed will be for account #1, while the password printed will be for account #2.
Change it so that you're only creating one account and printing the details for it:
int[] newAccount = myBank.AddNewAccount(Name, Balance);
System.out.println("Account Has been created\n Account number: " + newAccount[0]+"\nYour password : "+ newAccount[1]);
Also, while I tested your code, it seems you're calling withdraw() instead of deposit() in Bank.deposit():
accounts[i].withdraw(Money);
It's because myBank.AddNewAccount(Name, Balance) is getting called twice in below statement, actually it should be called only once per account.
System.out.println("Account Has been created\n Account number: " + myBank.AddNewAccount(Name, Balance)[0]+"\nYour password : "+ myBank.AddNewAccount(Name, Balance)[1]);
make below changes to your code and sit should work fine:
int[] arrDetails= myBank.AddNewAccount(Name, Balance);//added new line of code
System.out.println("Account Has been created\n Account number: " + arrDetails[0]+"\nYour password : "+ arrDetails[1]);// modified existing code
Final code for Case 1 should be:
case 1 : System.out.println("Enter a customer name :");
Name = br.readLine();
System.out.println("Enter a opening balance :");
Balance = Double.parseDouble(br.readLine());
Thread.sleep(250);
System.out.println("Creating your account....");
Thread.sleep(500);
int[] arrDetails= myBank.AddNewAccount(Name, Balance);
System.out.println("Account Has been created\n Account number: " + arrDetails[0]+"\nYour password : "+ arrDetails[1]);
break;
Your problem is here:
System.out.println("Account Has been created\n Account number: " + myBank.AddNewAccount(Name, Balance)[0]+"\nYour password : "+ myBank.AddNewAccount(Name, Balance)[1]);
Why do you add a new account twice in the above method? This creates a duplicate account with a different password. Change the above line to this.
myBank.AddNewAccount(Name, Balance);
System.out.println("Account Has been created\n Account number: " + myBank.getAccountNum()[0].+"\nYour password : "+ myBank.getAccountNum()[1]);
Your creating two objects and returning second obj password.
System.out.println("Account Has been created\n Account number: " + myBank.AddNewAccount(Name, Balance)[0]+"\nYour password : "+ myBank.AddNewAccount(Name, Balance)[1]);
In Above code your calling myBank.AddNewAccount two times so, it is creating two objects and THE PASSWORD YOUR PRINTING IS SECOND OBJECT PASSWORD, that's why it is showing wrong password.
you can use this code.
int[] details = myBank.AddNewAccount(Name, Balance);
System.out.println("Account Has been created\n Account number: " + details [0]+"\nYour password : "+ details[1]);

Java switch results (needing to print the values)

I cannot figure this out, I have created a switch in Java for a user to enter specific details. I have created a print statement inside the case to print the result that has been entered. What I want to happen is for a separate print statement to display the combined details of the values entered (after say a few loops). Any help will be greatly appreciated.
Thanks in advance.
Here is my code
import java.util.Scanner;
public class Stage3Check {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Setup an exit statement
boolean quit = false;
while (!quit){
System.out.println("Enter one of the following commands:");
System.out.println("1 - Damage Repair");
System.out.println("2 - Traffic Infringement");
System.out.println("3 - Exit Menu");
int choiceEntry = Integer.parseInt(input.nextLine());
//Create switch
if (choiceEntry <1){
System.out.println("Please enter a valid menu command (1-3)");
}
else if (choiceEntry >3){
System.out.println("Please enter a valid menu command (1-3)");
}
double damageCost = 0;
switch (choiceEntry){
case 1: System.out.print("Enter a description of the damage:");
String damageDetail = input.nextLine();
System.out.print("Enter the damage cost:");
damageCost = Integer.parseInt(input.nextLine());
System.out.print("The damage is: " + damageDetail + "\n");
System.out.print("The damage cost is: " + "$" + damageCost + "\n");
break;
case 2: System.out.print("Enter a description of the traffic infringement:");
String trafficDetail = input.nextLine();
System.out.print("Enter the traffic infringement cost:");
double trafficCost = Integer.parseInt(input.nextLine());
break;
case 3: quit = true;
System.out.println("Menu entry has been terminated.");
break;
}
System.out.print("The damage cost is: " + "$" + damageCost + "\n");
}
}
}
You could try adding the option to an arraylist.
List<String> listOfEntries=new ArrayList<String>(); // Add strings like damage repair,etc
//Or you could try
List<Integer> listOfOptions=new ArrayList<Integer>();// Add option here, like 1,2
You can add the user chosen options and at any point of time, you can retreive the options chosen by the user and display the values to the user.
Hope this helps!
This would work:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Setup an exit statement
boolean quit = false;
double dCost=0;
double tCost=0;
StringBuilder dDetail= new StringBuilder("The Damage Details are :" );
StringBuilder tDetail= new StringBuilder("The Traffic details are: " );
while (!quit){
System.out.println("Enter one of the following commands:");
System.out.println("1 - Damage Repair");
System.out.println("2 - Traffic Infringement");
System.out.println("3 - Exit Menu");
int choiceEntry = Integer.parseInt(input.nextLine());
//Create switch
if (choiceEntry <1){
System.out.println("Please enter a valid menu command (1-3)");
}
else if (choiceEntry >3){
System.out.println("Please enter a valid menu command (1-3)");
}
double damageCost = 0;
switch (choiceEntry){
case 1: System.out.print("Enter a description of the damage:");
String damageDetail = input.nextLine();
System.out.print("Enter the damage cost:");
damageCost = Integer.parseInt(input.nextLine());
System.out.print("The damage is: " + damageDetail + "\n");
System.out.print("The damage cost is: " + "$" + damageCost + "\n");
dDetail.append(damageDetail+"\n");
dCost=dCost+damageCost;
break;
case 2: System.out.print("Enter a description of the traffic infringement:");
String trafficDetail = input.nextLine();
System.out.print("Enter the traffic infringement cost:");
double trafficCost = Integer.parseInt(input.nextLine());
tDetail.append( trafficDetail+"\n");
tCost=tCost+trafficCost;
break;
case 3: quit = true;
System.out.println("Menu entry has been terminated.");
System.out.println("the Total traffic cost is "+tCost);
System.out.println("the Total Damage cost is "+dCost);
System.out.println(tDetail);
System.out.println(dDetail);
break;
}
}
}
Use StringBuilder to append your data. PFB updated code :
import java.util.Scanner;
public class Stage3Check {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Setup an exit statement
boolean quit = false;
StringBuilder sb = new StringBuilder();
outer: while (!quit) {
System.out.println("Enter one of the following commands:");
System.out.println("1 - Damage Repair");
System.out.println("2 - Traffic Infringement");
System.out.println("3 - Exit Menu");
int choiceEntry = Integer.parseInt(input.nextLine());
// Create switch
if (choiceEntry < 1 || choiceEntry > 3)
continue outer;
double damageCost = 0;
switch (choiceEntry) {
case 1:
System.out.print("Enter a description of the damage:");
String damageDetail = input.nextLine();
System.out.print("Enter the damage cost:");
damageCost = Integer.parseInt(input.nextLine());
sb.append("The damage is: " + damageDetail + "\n");
sb.append("The damage cost is: " + "$" + damageCost + "\n");
break;
case 2:
System.out
.print("Enter a description of the traffic infringement:");
String trafficDetail = input.nextLine();
System.out.print("Enter the traffic infringement cost:");
double trafficCost = Integer.parseInt(input.nextLine());
sb.append("The traffic infringement is: " + trafficDetail
+ "\n");
sb.append("The traffic infringement cost is: " + "$"
+ trafficCost + "\n");
break;
default:
quit = true;
System.out.println("Menu entry has been terminated.");
break;
}
}
System.out.println(sb.toString());
}
}
1- The print statement should be placed outside the while loop:
System.out.print("The damage cost is: " + "$" + damageCost + "\n");
2- Declare the damageCost variable globally i.e outside the while loop.
3- Change the statement:
double trafficCost = Integer.parseInt(input.nextLine());
to
damageCost = damageCost + Integer.parseInt(input.nextLine());

Arrays and bank accounts in Java

I am trying to write a simple Bank Account Management program that does the following:
Creates a new account with Account number and Balance taken from user and stored in an array
Selects an account (from the array)
Deletes the account selected
Withdraw and Deposit into account selected.
Problem: I don't understand what the my mistakes are.
I tried using different types of arrays for account number and balance storing, but I didn't not find the answer yet. I search the web and Stackoverflow for references, documentations, simple examples, but could not find any (the ones that I found, use some commands and things that I haven't learned yet so I can understand how they work). I am a beginner, I am still learning and would appreciate some advice. Thanks!
//Bank account class
public class account {
private int ANumber;
private double balance;
public account(double initialBalance, int accno) {
balance = initialBalance;
ANumber = accno;
}
public void deposit (double u_amm){
balance += u_amm;
}
public double withdraw(double amount) {
balance -= amount;
return amount;
}
public double getBalance() {
return balance;
}
public int getAccount(){
return ANumber;
}
}
And this is the Main class
import java.util.Scanner;
// main class
public class bankmain {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// Menu starts from here
Scanner input = new Scanner(System.in);
System.out.println("Enter the option for the operation you need:");
System.out.println("****************************************************");
System.out.println("[ Options: ne - New Account de - Delete Account ]");
System.out.println("[ dp - Deposit wi - Withdraw ]");
System.out.println("[ se - Select Account ex - Quit ]");
System.out.println("****************************************************");
System.out.print("> "); //indicator for user input
String choice = input.next();
//Options
while(true){
if(choice == "ne"){
int nacc;
int bal;
int [][]array = new int[nacc][bal]; // Array for account and balance
System.out.print("Insert account number: ");
nacc =input.nextInt(); //-- Input nr for array insertion
System.out.print("Enter initial balance: ");
bal=input.nextInt(); //-- Input nr for array insertion
System.out.println("Current account: " + nacc + " " + "Balance " + bal);
break;
}
// account selection
if(choice.equals("se")){
System.out.println("Enter number of account to be selected: ");
//user input for account nr from array
System.out.println("Account closed.");
}
//close account
if(choice.equals("de")){
//array selected for closing
System.out.println("Account closed.");
}
// deposit
if(choice.equals("dp")){
System.out.print("Enter amount to deposit: ");
double amount = scan.nextDouble();
if(amount <= 0){
System.out.println("You must deposit an amount greater than 0.");
} else {
System.out.println("You have deposited " + (amount + account.getBalance()));
}
}
// withdrawal
if(choice.equals("wi")){
System.out.print("Enter amount to be withdrawn: ");
double amount = scan.nextDouble();
if (amount > account.balance()){
System.out.println("You can't withdraw that amount!");
} else if (amount <= account.balance()) {
account.withdraw(amount);
System.out.println("NewBalance = " + account.getBalance());
}
}
//quit
if(choice == "ex"){
System.exit(0);
}
} // end of menu loop
}// end of main
} // end of class
Your code was wrong on many levels - first try to work on your formatting and naming conventions so you don't learn bad habbits. Dont use small leters for naming classes, try to use full words to describe variables and fields, like in that Account.class example:
public class Account {
private Integer accountNumber;
private Double balance;
public Account(final Integer accountNumber, final Double initialBalance) {
this.accountNumber = accountNumber;
balance = initialBalance;
}
public Double deposit (double depositAmmount) {
balance += depositAmmount;
return balance;
}
public Double withdraw(double withdrawAmmount) {
balance -= withdrawAmmount;
return balance;
}
public Double getBalance() {
return balance;
}
public Integer getAccountNumber() {
return accountNumber;
}
}
Also try to use the same formatting(ie. spaces after brackets) in all code, so that it's simpler for you to read.
Now - what was wrong in your app:
Define the proper holder for your accounts i.e. HashMap that will hold the information about all accounts and will be able to find them by accountNumber.
HashMap<Integer, Account> accountMap = new HashMap<Integer, Account>();
This one should be inside your while loop, as you want your user to do multiple tasks. You could ommit the println's but then the user would have to go back to the top of the screen to see the options.
System.out.println("Enter the option for the operation you need:");
System.out.println("****************************************************");
System.out.println("[ Options: ne - New Account de - Delete Account ]");
System.out.println("[ dp - Deposit wi - Withdraw ]");
System.out.println("[ se - Select Account ex - Quit ]");
System.out.println("****************************************************");
System.out.print("> "); //indicator for user input
String choice = input.nextLine();
System.out.println("Your choice: " + choice);
You shouldn't compare Strings using '==' operator as it may not return expected value. Take a look at: How do I compare strings in Java? or What is the difference between == vs equals() in Java?. For safty use Objects equals instead, ie:
choice.equals("ne")
There was no place where you created the account:
Account newAccount = new Account(newAccountNumber, initialBalance);
You didn't use if-else, just if's. It should look more like that (why to check if the choice is 'wi' if it was already found to be 'ne'):
if(choice.equals("ne")) {
//doStuff
} else if choice.equals("se") {
//doStuff
} //and so on.
If your using Java version >= 7 then instead of if-else you can use switch to compare Strings.
There was no notification of the wrong option:
} else {
System.out.println("Wrong option chosen.");
}
You didn't close your Scanner object. This really doesn't matter here, as it's in main method and will close with it, but it's a matter of good habbits to always close your streams, data sources etc when done using it:
input.close();
So the whole code can look like this:
import java.util.HashMap;
import java.util.Scanner;
// main class
public class BankAccount {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
HashMap<Integer, Account> accountMap = new HashMap<Integer, Account>();
//Options
while(true) {
System.out.println("Enter the option for the operation you need:");
System.out.println("****************************************************");
System.out.println("[ Options: ne - New Account de - Delete Account ]");
System.out.println("[ dp - Deposit wi - Withdraw ]");
System.out.println("[ se - Select Account ex - Quit ]");
System.out.println("****************************************************");
System.out.print("> "); //indicator for user input
String choice = input.next();
System.out.println("Your choice: " + choice);
if(choice.equals("ne")) {
Integer newAccountNumber;
Double initialBalance;
Account newAccount;
// Array for account and balance
System.out.print("Insert account number: ");
newAccountNumber = input.nextInt(); //-- Input nr for array insertion
System.out.print("Enter initial balance: ");
initialBalance=input.nextDouble(); //-- Input nr for array insertion
newAccount = new Account(newAccountNumber, initialBalance);
accountMap.put(newAccountNumber, newAccount);
System.out.println("New Account " + newAccountNumber + " created with balance: " + initialBalance);
}
//select account
else if(choice.equals("se")) {
System.out.println("Enter number of account to be selected: ");
Integer accountToGetNumber = input.nextInt();
Account returnedAccount = accountMap.get(accountToGetNumber);
if (returnedAccount != null)
{
System.out.println("Account open. Current balance: " + returnedAccount.getBalance());
}
else
{
//user input for account nr from array
System.out.println("Account does not exist.");
}
}
//close account
else if(choice.equals("de"))
{
System.out.println("Enter number of account to be selected: ");
Integer accountToDeleteNumber = input.nextInt();
Account removedAccount = accountMap.remove(accountToDeleteNumber);
if (removedAccount != null)
{
System.out.println("Account " + removedAccount.getAccountNumber() + " has been closed with balance: " + removedAccount.getBalance());
}
else
{
//user input for account nr from array
System.out.println("Account does not exist.");
}
}
// deposit
else if(choice.equals("dp")) {
System.out.println("Enter number of account to deposit: ");
Integer accountToDeposit = input.nextInt();
System.out.print("Enter amount to deposit: ");
double amount = input.nextDouble();
if(amount <= 0){
System.out.println("You must deposit an amount greater than 0.");
} else {
accountMap.get(accountToDeposit).deposit(amount);
System.out.println("You have deposited " + (amount));
System.out.println("Current balance " + accountMap.get(accountToDeposit).getBalance());
}
}
// withdrawal
else if(choice.equals("wi")) {
System.out.println("Enter number of account to withdraw: ");
Integer accountToWithdraw = input.nextInt();
System.out.print("Enter amount to withdraw: ");
double amount = input.nextDouble();
if(amount <= 0) {
System.out.println("You must deposit an amount greater than 0.");
} else {
accountMap.get(accountToWithdraw).withdraw(amount);
System.out.println("You have deposited " + (amount));
System.out.println("Current balance " + accountMap.get(accountToWithdraw).getBalance());
}
}
//quit
else if(choice.equals("ex")) {
break;
} else {
System.out.println("Wrong option.");
} //end of if
} //end of loop
input.close();
} //end of main
} //end of class
There still is much to improve, i.e. input validation - but this should work for the begining.
You have written the above code, but it has many mistakes. You need to learn the The basics of Java programming.
I have modified your program to perform below operations :-
Create new account.
Select existing account.
Deposit amount.
Withdraw amount.
View balance.
Delete account.
Exit.
Account.java :
/**
* This class performs bank operations
*/
public class Account {
private int accNumber;
private double balance;
public Account(double initialBalance, int accNo) {
balance = initialBalance;
accNumber = accNo;
}
public void deposit(double amount) {
balance += amount;
}
public double withdraw(double amount) {
balance -= amount;
return amount;
}
public double getBalance() {
return balance;
}
public int getAccNumber() {
return accNumber;
}
}
BankMain.java :
public class BankMain {
private static double amount;
private static ArrayList<Account> accountList = new ArrayList<>();
private static Account selectedAccount;
private static boolean flag = false;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// Menu starts from here
Scanner input = new Scanner(System.in);
System.out.println("Enter the option for the operation you need:");
System.out
.println("****************************************************");
System.out
.println("[ Options: new - New Account del - Delete Account ]");
System.out
.println("[ dp - Deposit wi - Withdraw bal - Check balance ]");
System.out
.println("[ se - Select Account exit - Quit ]");
System.out
.println("****************************************************");
Account account = null;
while (true) {
System.out.println("> "); // indicator for user input
String choice = input.next();
// Options
switch (choice) {
case "new":
// Create new account
int accNo = 0;
int bal = 0;
System.out.println("Enter account number : ");
accNo = input.nextInt();
System.out.println("Enter initial balance: ");
bal = input.nextInt();
System.out.println("Current account: " + accNo + " "
+ "Balance " + bal);
account = new Account(bal, accNo);
accountList.add(account);
break;
case "se":
// select account
System.out
.println("Enter account number for further operations : ");
int selectedAcc = scan.nextInt();
System.out.println("Selected account : " + selectedAcc);
for (Object object : accountList) {
selectedAccount = (Account) object;
if (selectedAccount.getAccNumber() == selectedAcc) {
flag = true;
break;
} else {
flag = false;
}
}
if (!flag) {
System.out.println("Account doesn't exists.");
}
if (accountList.size() == 0) {
System.out.println("Zero account exists.");
}
break;
case "del":
// close account
System.out
.println("Enter account number for further operations : ");
int selectedAcc1 = scan.nextInt();
System.out.println("Selected account : " + selectedAcc1);
Iterator<Account> iterator = accountList.iterator();
while (iterator.hasNext()) {
selectedAccount = (Account) iterator.next();
if (selectedAccount.getAccNumber() == selectedAcc1) {
iterator.remove();
flag = true;
break;
}
}
if (!flag) {
System.out.println("Account doesn't exists.");
}
System.out.println("Account " + selectedAcc1 + " closed.");
break;
case "dp":
// Deposit amount
System.out.println("Enter amount to deposit : ");
amount = scan.nextDouble();
if (amount <= 0) {
System.out
.println("You must deposit an amount greater than 0.");
} else {
if (flag) {
selectedAccount.deposit(amount);
System.out.println("You have deposited " + amount
+ ". Total balance : "
+ (selectedAccount.getBalance()));
} else {
System.out.println("Please select account number.");
}
}
break;
case "wi":
// Withdraw amount
System.out.println("Enter amount to be withdrawn: ");
amount = scan.nextDouble();
if (amount > account.getBalance() && amount <= 0) {
System.out.println("You can't withdraw that amount!");
} else if (amount <= selectedAccount.getBalance()) {
if (flag) {
selectedAccount.withdraw(amount);
System.out.println("You have withdraw : " + amount
+ " NewBalance : "
+ selectedAccount.getBalance());
} else {
System.out.println("Please select account number.");
}
}
break;
case "bal":
// check balance in selected account
if (flag) {
System.out.println("Your current account balance : "
+ selectedAccount.getBalance());
} else {
System.out.println("Please select account number.");
}
break;
case "exit":
default:
// quit
System.out.println("Thank You. Visit Again!");
flag = false;
input.close();
scan.close();
System.exit(0);
break;
}
} // end of menu loop
}// end of main
} // end of class
I have tested this code & it is working fine.
Output :
Enter the option for the operation you need:
****************************************************
[ Options: new - New Account del - Delete Account ]
[ dp - Deposit wi - Withdraw bal - Check balance ]
[ se - Select Account exit - Quit ]
****************************************************
> new
Enter account number : 101
Enter initial balance: 10000
Current account: 101 Balance 10000
> new
Enter account number : 102
Enter initial balance: 25000
Current account: 102 Balance 25000
> se
Enter account number for further operations : 103
Selected account : 103
Account doesn't exists.
> se
Enter account number for further operations : 101
Selected account : 101
> bal
Your current account balance : 10000.0
> dp
Enter amount to deposit : 2500
You have deposited 2500.0. Total balance : 12500.0
> wi
Enter amount to be withdrawn: 500
You have withdraw : 500.0 NewBalance : 12000.0
> se
Enter account number for further operations : 102
Selected account : 102
> bal
Your current account balance : 25000.0
> del
Enter account number for further operations : 101
Selected account : 101
Account 101 closed.
> se
Enter account number for further operations : 101
Selected account : 101
Account doesn't exists.
> exit
Thank You. Visit Again!

Getting a Null Pointer Exception and not sure how to fix it [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I am creating a tester class for a simple input database program. I do not have to store information nor delete anything, but there are two arrays in my the class I am running my tester class for.
This is my tester class:
import java.util.Scanner;
public class Asst_3 {
private static Scanner keyboard;
public Asst_3(){
this.keyboard = new Scanner(System.in);
}
public static void main(String[]args){
Policy insurance = new Policy();
insurance.setCustomerLast(null);
insurance.setCustomerFirst(null);
insurance.setPolicyNumber();
insurance.setAge();
insurance.setAccidentNumber();
insurance.setPremiumDueDate(00,00,0000);
//insurance.toString();
System.out.println("Welcome to Drive-Rite Insurance Company");
showMenuOptions();
Scanner keyboard = new Scanner(System.in);
int choice = keyboard.nextInt();
intiateMenuSelection(choice);
}
private static void intiateMenuSelection(int selectedOption) {
switch (selectedOption){
case 1: newPolicy(null);
break;
case 2: returnFromAge();
break;
case 3: returnFromDue();
break;
case 4: System.out.println("Goodbye");
System.exit(0);
break;
default: break;
}
}
private static void newPolicy(Policy insurance) {
System.out.println("Enter Customer's Policy Number: ");
int poliNum = keyboard.nextInt();
insurance.getPolicyNumber();
System.out.println("Customer's Policy Number is: " + keyboard.nextInt());
System.out.println("Enter Customer's Last Name: ");
String custLast = keyboard.nextLine();
insurance.getCustomerLast();
System.out.println("Customer's Last Name is: " + keyboard.nextInt());
System.out.println("Enter Customer's First Name: ");
String custFirst = keyboard.nextLine();
insurance.getCustomerFirst();
System.out.println("Customer's First Name is: " + keyboard.nextInt());
System.out.println("Enter Customer's Age: ");
int custAge = keyboard.nextInt();
insurance.getAge();
System.out.println("Customer's Age is: " + keyboard.nextInt());
System.out.println("Enter Customer's Amount of Previous Accident Reaports in Past 3 years: ");
int custAccident = keyboard.nextInt();
insurance.getAccidentNumber();
System.out.println("Customer's Amount of Accidents is: " + keyboard.nextInt());
System.out.println("Enter Customer's next Premium Due Date: ");
int dueDate = keyboard.nextInt();
insurance.getPremiumDueDate();
System.out.println("Customer's Next Due Date is: " + keyboard.nextInt());
insurance.toString();
showMenuOptions();
}
private static void returnFromDue() {
showMenuOptions();
}
private static void returnFromAge() {
showMenuOptions();
}
private static void returnToMenu() {
intiateMenuSelection(0);
}
private static void showMenuOptions() {
System.out.println("Choose a menu option: ");
System.out.println("(1) Create New Policies");
System.out.println("(2) Search by age");
System.out.println("(3) Search by due date");
System.out.println("(4) Exit");
System.out.print("Input Option Number ---> ");
}
}
And the Null Pointer Error:
Exception in thread "main" java.lang.NullPointerException
at Asst_3.newPolicy(Asst_3.java:55)
at Asst_3.intiateMenuSelection(Asst_3.java:40)
at Asst_3.main(Asst_3.java:35)
This is the class I'm making my tester for:
import java.util.*;
public class Policy {
private int policyNumber;
private int age;
private int accidentNumber;
private String customerLast;
private String customerFirst;
private int [] months;
private int [] premiumDueDate;
public Policy() {
this.policyNumber = 0;
this.age = 0;
this.accidentNumber = 0;
this.customerLast = "";
this.customerFirst = "";
this.premiumDueDate = new int [3];
this.premiumDueDate[0] = 0;
this.premiumDueDate[1] = 0;
this.premiumDueDate[2] = 0;
this.months = new int [12];
this.months[0] = this.months[2] = this.months[4] = this.months[6] = this.months[7] = this.months[9] = this.months[11] = 31;
this.months[1] = 28;
this.months[3] = this.months[5] = this.months[8] = this.months[10] = 30;
}
public int getPolicyNumber(){
return this.policyNumber;
}
public void setPolicyNumber(){
if(policyNumber < 1000){
policyNumber = 0;
}
if(policyNumber > 9999){
policyNumber = 0;
}
}
public int[] getPremiumDueDate(){
return this.premiumDueDate;
}
public void setPremiumDueDate(int month, int day, int year){
this.premiumDueDate[0] = month;
this.premiumDueDate[1] = day;
this.premiumDueDate[2] = year;
if(month < 0||month >= 12)
{
this.premiumDueDate[0] = 0;
this.premiumDueDate[1] = 0;
this.premiumDueDate[2] = 0;
}
else if(day < 0 || day > this.months[month])
{
this.premiumDueDate[0] = 0;
this.premiumDueDate[1] = 0;
this.premiumDueDate[2] = 0;
}
}
public int getAge(){
return this.age;
}
public void setAge(){
this.age = 0;
}
public int getAccidentNumber(){
return this.accidentNumber;
}
public void setAccidentNumber(){
this.accidentNumber = 0;
}
public String getCustomerLast(){
return this.customerLast;
}
public void setCustomerLast(String customerLast){
this.customerLast = customerLast;
}
public String getCustomerFirst(){
return this.customerFirst;
}
public void setCustomerFirst(String customerFirst){
this.customerFirst = customerFirst;
}
public String toString(){
return "\n Policy Number: " + this.policyNumber + "\n Customer Last Name: " + this.customerLast + "\n Customer First Name: " + this.customerFirst
+ "\n Customer age: " + this.age + "\n Number of Accidents in Past Three Years: " + this.accidentNumber + "\n Premium Due Date: " + this.premiumDueDate;
}
}
Thank you everyone, your amazing!
Here's my edited code:
The Tester
import java.util.Scanner;
public class Asst_3 {
private static Scanner keyboard;
public Asst_3(){
this.keyboard = new Scanner(System.in);
}
public static void main(String[]args){
System.out.println("Welcome to Drive-Rite Insurance Company");
showMenuOptions();
int choice = keyboard.nextInt();
intiateMenuSelection(choice);
}
private static void intiateMenuSelection(int selectedOption) {
switch (selectedOption){
case 1: newPolicy(new Policy());
break;
case 2: returnFromAge();
break;
case 3: returnFromDue();
break;
case 4: System.out.println("Goodbye");
System.exit(0);
break;
default: break;
}
}
private static void newPolicy(Policy insurance) {
System.out.println("Enter Customer's Policy Number: ");
int poliNum = keyboard.nextInt();
insurance.setPolicyNumber(poliNum);
System.out.println("Customer's Policy Number is: " + insurance.getPolicyNumber());
System.out.println("Enter Customer's Last Name: ");
String custLast = keyboard.nextLine();
insurance.setCustomerLast(custLast);
System.out.println("Customer's Last Name is: " + insurance.getCustomerLast());
System.out.println("Enter Customer's First Name: ");
String custFirst = keyboard.nextLine();
insurance.setCustomerFirst(custFirst);
System.out.println("Customer's First Name is: " + insurance.getCustomerFirst());
System.out.println("Enter Customer's Age: ");
int custAge = keyboard.nextInt();
insurance.setAge(custAge);
System.out.println("Customer's Age is: " + insurance.getAge());
System.out.println("Enter Customer's Amount of Previous Accident Reaports in Past 3 years: ");
int custAccident = keyboard.nextInt();
insurance.setAccidentNumber(custAccident);
System.out.println("Customer's Amount of Accidents is: " + insurance.getAccidentNumber());
System.out.println("Enter Customer's next Premium Due Date: ");
int dueDate = keyboard.nextInt();
insurance.setPremiumDueDate(dueDate, dueDate, dueDate);
System.out.println("Customer's Next Due Date is: " + insurance.getPremiumDueDate());
insurance.toString();
returnToMenu();
}
private static void returnFromDue() {
showMenuOptions();
}
private static void returnFromAge() {
showMenuOptions();
}
private static void returnToMenu() {
intiateMenuSelection(0);
}
private static void showMenuOptions() {
System.out.println("Choose a menu option: ");
System.out.println("(1) Create New Policies");
System.out.println("(2) Search by age");
System.out.println("(3) Search by due date");
System.out.println("(4) Exit");
System.out.print("Input Option Number ---> ");
}
}
And the class being tested:
import java.util.*;
public class Policy {
private int policyNumber;
private int age;
private int accidentNumber;
private String customerLast;
private String customerFirst;
private int [] months;
private int [] premiumDueDate;
public Policy() {
this.policyNumber = 0;
this.age = 0;
this.accidentNumber = 0;
this.customerLast = "";
this.customerFirst = "";
this.premiumDueDate = new int [3];
this.premiumDueDate[0] = 0;
this.premiumDueDate[1] = 0;
this.premiumDueDate[2] = 0;
this.months = new int [12];
this.months[0] = this.months[2] = this.months[4] = this.months[6] = this.months[7] = this.months[9] = this.months[11] = 31;
this.months[1] = 28;
this.months[3] = this.months[5] = this.months[8] = this.months[10] = 30;
}
public int getPolicyNumber(){
return this.policyNumber;
}
public void setPolicyNumber(int policyNumber){
if(policyNumber < 1000){
policyNumber = 0;
}
if(policyNumber > 9999){
policyNumber = 0;
}
}
public int[] getPremiumDueDate(){
return this.premiumDueDate;
}
public void setPremiumDueDate(int month, int day, int year){
this.premiumDueDate[0] = month;
this.premiumDueDate[1] = day;
this.premiumDueDate[2] = year;
if(month < 0||month >= 12)
{
this.premiumDueDate[0] = 0;
this.premiumDueDate[1] = 0;
this.premiumDueDate[2] = 0;
}
else if(day < 0 || day > this.months[month])
{
this.premiumDueDate[0] = 0;
this.premiumDueDate[1] = 0;
this.premiumDueDate[2] = 0;
}
}
public int getAge(){
return this.age;
}
public void setAge(int age){
this.age = 0;
}
public int getAccidentNumber(){
return this.accidentNumber;
}
public void setAccidentNumber(int accidentNumber){
this.accidentNumber = 0;
}
public String getCustomerLast(){
return this.customerLast;
}
public void setCustomerLast(String customerLast){
this.customerLast = customerLast;
}
public String getCustomerFirst(){
return this.customerFirst;
}
public void setCustomerFirst(String customerFirst){
this.customerFirst = customerFirst;
}
public String toString(){
return "\n Policy Number: " + this.policyNumber + "\n Customer Last Name: " + this.customerLast + "\n Customer First Name: " + this.customerFirst
+ "\n Customer age: " + this.age + "\n Number of Accidents in Past Three Years: " + this.accidentNumber + "\n Premium Due Date: " + this.premiumDueDate;
}
}
But now I have a new error after executing the program:
Welcome to Drive-Rite Insurance Company
Choose a menu option:
(1) Create New Policies
(2) Search by age
(3) Search by due date
(4) Exit
Input Option Number ---> Exception in thread "main" java.lang.NullPointerException
at Asst_3.main(Asst_3.java:23)
Here's an updated version with that NPE fixed:
import java.util.Scanner;
public class Asst_3 {
private static Scanner keyboard;
public static void main(String[]args){
System.out.println("Welcome to Drive-Rite Insurance Company");
showMenuOptions();
this.keyboard = new Scanner(System.in);
int choice = keyboard.nextInt();
intiateMenuSelection(choice);
}
private static void intiateMenuSelection(int selectedOption) {
switch (selectedOption){
case 1: newPolicy(new Policy());
break;
case 2: returnFromAge();
break;
case 3: returnFromDue();
break;
case 4: System.out.println("Goodbye");
System.exit(0);
break;
default: break;
}
}
private static void newPolicy(Policy insurance) {
System.out.println("Enter Customer's Policy Number: ");
int poliNum = keyboard.nextInt();
insurance.setPolicyNumber(poliNum);
System.out.println("Customer's Policy Number is: " + insurance.getPolicyNumber());
System.out.println("Enter Customer's Last Name: ");
String custLast = keyboard.nextLine();
insurance.setCustomerLast(custLast);
System.out.println("Customer's Last Name is: " + insurance.getCustomerLast());
System.out.println("Enter Customer's First Name: ");
String custFirst = keyboard.nextLine();
insurance.setCustomerFirst(custFirst);
System.out.println("Customer's First Name is: " + insurance.getCustomerFirst());
System.out.println("Enter Customer's Age: ");
int custAge = keyboard.nextInt();
insurance.setAge(custAge);
System.out.println("Customer's Age is: " + insurance.getAge());
System.out.println("Enter Customer's Amount of Previous Accident Reaports in Past 3 years: ");
int custAccident = keyboard.nextInt();
insurance.setAccidentNumber(custAccident);
System.out.println("Customer's Amount of Accidents is: " + insurance.getAccidentNumber());
System.out.println("Enter Customer's next Premium Due Date: ");
int dueDate = keyboard.nextInt();
insurance.setPremiumDueDate(dueDate, dueDate, dueDate);
System.out.println("Customer's Next Due Date is: " + insurance.getPremiumDueDate());
insurance.toString();
returnToMenu();
}
private static void returnFromDue() {
showMenuOptions();
}
private static void returnFromAge() {
showMenuOptions();
}
private static void returnToMenu() {
intiateMenuSelection(0);
}
private static void showMenuOptions() {
System.out.println("Choose a menu option: ");
System.out.println("----------------------------------------");
System.out.println("(1) Create New Policies");
System.out.println("(2) Search by age");
System.out.println("(3) Search by due date");
System.out.println("(4) Exit");
System.out.print("Input Option Number ---> ");
}
}
The errors are I'm having issues with they keyboard variables.
null pointer occurring in
private static void newPolicy(Policy insurance)
this method. For these lines
insurance.getPolicyNumber();
insurance.get....();
insurance.get....();
because the reference/object insurance coming as a parameter from where its being called . in you case you are passing null to the method
newPolicy(null); //try to pass a reference of Policy like 'newPolicy(new Policy())' .
You declare keybord twice.
remove the Scanner from this line:
Scanner keyboard = new Scanner(System.in);
So you have:
keyboard = new Scanner(System.in);
You're shadowing you variables, that is, you've declared keyboard as a class variable
public class Asst_3 {
private static Scanner keyboard;
But in the main, you've re-declared it as a local variable...
Scanner keyboard = new Scanner(System.in);
Which means that the class variable is still null when you call newPolicy.
Start by removing the re-declaration...
//Scanner keyboard = new Scanner(System.in);
keyboard = new Scanner(System.in);
Which will lead you smack bang into you next NullPointerException in newPolicy
insurance.getPolicyNumber();
Caused by the fact that you call the method passing it a null value...
newPolicy(null);
I'll leave you to fix that ;)
Hint: newPolicy should take no parameters and should return an new instance of Policy which can then manipulated by the other methods ;)
The insurance that you are passing to newPolicy is null
case 1: newPolicy(null);
hence
insurance.getPolicyNumber();
will throw a NPE

How do I access my array in my method?

Here is my issue. I am trying to build an array of HomeLoan in my main, and then from my main, call the printHLoans(hLoans) from my main, so that I can list them and then add more functionality. Unfortunately, it is saying that hLoan cannot be resolved as a variable.
Main Class
import java.util.InputMismatchException;
import java.util.Scanner;
public class LoanTest
{
static int term;
static int loanID=0;
static int hHowMany=0;
static int cHowMany=0;
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
System.out.print("Enter name: ");
String name = input.nextLine();
System.out.print("Enter Customer ID: ");
int custID=0;
do
{
try
{
custID = input.nextInt();
}
catch (InputMismatchException e)
{
System.out.println("Customer IDs are numbers only");
input.next();
}
}while (custID<1);
boolean aa=true;
while(aa)
{
System.out.println("Do you have a (h)ome loan or a (c)ar loan?");
String a = input.next();
switch (a)
{
case "h": System.out.println("You selected Home Loan");
System.out.println("How many Home Loans would you like to enter?");
hHowMany = input.nextInt();
HomeLoan[] hLoans = new HomeLoan[hHowMany];
int z=0;
while (hHowMany>z)
{
hLoans[z] = new HomeLoan(name, custID);
z++;
}
break;
case "c": System.out.println("You selected Car Loan");
System.out.println("How many Car Loans would you like to enter?");
cHowMany = input.nextInt();
int x=0;
CarLoan[] carLoans = new CarLoan[cHowMany];
while (x<cHowMany)
{
System.out.print("Enter Loan ID: ");
loanID=0;
do
{
try
{
loanID=input.nextInt();
}
catch (InputMismatchException e)
{
System.out.println("Loan IDs are number only");
input.next();
}
}while (loanID<1);
boolean b=true;
while(b)
{
System.out.print("Enter term: ");
term=input.nextInt();
boolean t = CarLoan.termCorrect(term);
if(t){System.out.println("Error: Maximum of 6 year");}
else {b=false; System.out.println("You entered: " + term + " years");}
}
carLoans[x] = new CarLoan(name, custID, loanID, term);
x++;
}
break;
default: System.out.println("Invalid input");
break;
}
System.out.print("Would you like to enter another loan?");
System.out.print("(y)es or (n)o:");
String m = input.next();
System.out.println("");
switch (m)
{
case "y": break;
case "n": aa=false;
break;
default: System.out.print("Invalid entry");
}
}
printHLoans(hLoans);
System.out.println("Thank you for using Loan Software");
System.out.println("Have a nice day");
}
public static void printHLoans(HomeLoan hLoans[])
{
System.out.println("Here are the loans you entered . . .");
int zzz=0;
while (zzz<hHowMany)
{
term = hLoans[zzz].getTerm();
loanID=hLoans[zzz].getLoanID();
String address=hLoans[zzz].getAddress();
double loanAmount = hLoans[zzz].getLoanAmount();
System.out.print(zzz + ": ");
System.out.print(hLoans[zzz].toString(loanID, address, term, loanAmount));
System.out.println();
zzz++;
}
}
}
HomeLoan Class
import java.util.InputMismatchException;
import java.util.Scanner;
public class HomeLoan extends Loan
{
private String address;
int howMany;
private double loanAmount;
private int term;
private int loanID;
public HomeLoan()
{
}
public HomeLoan(String name, int custID)
{
//super(name, custID, loanID);
Scanner input = new Scanner (System.in);
System.out.print("Enter Loan ID: ");
loanID=0;
do
{
try
{
loanID=input.nextInt();
}
catch (InputMismatchException e)
{
System.out.println("Loan IDs are number only");
input.next();
}
}while (loanID<1);
boolean l=true;
while (l)
{
System.out.print("Enter term: ");
term=input.nextInt();
boolean s = HomeLoan.termCorrect(term);
if (s){System.out.println("Error: Maximum of 30 years");}
else {l=false;}
}
//System.out.println();
input.nextLine();
System.out.print("Enter your address: ");
address=input.nextLine();
System.out.print("Enter loan ammount: ");
loanAmount = input.nextDouble();
double annualInterest = 10.99;
double monthlyPayment = amortization(loanAmount, annualInterest, term);
double newBalance=payment(monthlyPayment, loanAmount);
//System.out.println("Payment: " + monthlyPayment);
//System.out.println("New balance after payment: " + newBalance);
}
public static boolean termCorrect(int term)
{
boolean a;
if (term>30) {a=true; return a;}
else {a=false; return a;}
}
public String toString(String name, int custID, int loanID)
{
String display = "Name: " + name + " Customer ID: " + custID + " Address: "+ address+ " Loan ID: " + loanID + " Loan Amount: $" + loanAmount
+ " Current Balance: $";
return display;
}
public String getAddress()
{
return address;
}
public double getLoanAmount()
{
return loanAmount;
}
public int getTerm()
{
return term;
}
public int getLoanID()
{
return loanID;
}
public String toString(int loanID, String address, int term, double loanAmmount)
{
String displa = "ID: " + loanID + " Address:" + address + " Term: " + term + " Loan Ammount: " + loanAmmount;
return displa;
}
private void equals()
{
}
public void printHLoans(HomeLoan hLoans[], int xxx)
{
}
}
How do I make this work?
That's because you've declared the HomeLoan[] hLoans = new HomeLoan[hHowMany]; within the while loop and are trying to access it after that. That's why once the while loop is over, the hLoans goes out of scope. In your case, its more specifically within the case "h" of the switch, which further narrows down the scope of hLoans to just within it.
To be able to access it outside the while, you need to declare it at a scope higher than the while. Do something like this.
HomeLoan[] hLoans; // Before while
while(aa) {
...
switch..
case "h": hLoans = new HomeLoan[hHowMany];
}
printHLoans(hLoans);

Categories

Resources