How do I access my array in my method? - java

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

Related

How do I search or access an account I made in my banking system program?

I'm working on a baking system program for a school project which includes the ff. features:
Creating a new account
Balance Inquiry
Deposit
Withdraw
Close account
So far here's the code I've written:
class BankAccountAndaya {
private String accountName, address, birthday, contactNumber;
Scanner sc = new Scanner(System.in);
//default constructor
public BankAccountAndaya() {
}
public BankAccountAndaya(String accountName, String address, String birthday, String contactNumber){
this.accountName = accountName;
this.address = address;
this.birthday = birthday;
this.contactNumber = contactNumber;
}
//accessor
public String getAccountName() {
return accountName;
}
public String getAddress() {
return address;
}
public String getBirthday() {
return birthday;
}
public String getContactNumber() {
return contactNumber;
}
//mutators
public void setAccountName(String name) {
this.accountName = name;
}
public void setAddress(String address) {
this.address = address;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public void setContactNumber(String contactNum) {
this.contactNumber = contactNum;
}
public void getClientDetails() {
System.out.print("Enter name: ");
setAccountName(sc.next());
System.out.print("Enter address: ");
setAddress(sc.next());
System.out.print("Enter birthday (MM/DD/YY): ");
setBirthday(sc.next());
System.out.print("Enter contact number: ");
setContactNumber(sc.next());
}
}
public class SavingsAccountAndaya extends BankAccountAndaya {
private int accountNo;
private double balance, interestRate;
Random rd = new Random();
Scanner sc = new Scanner(System.in);
// default constructor
SavingsAccountAndaya() {
}
// accessors
public int getAccountNo() {
return accountNo;
}
public double getBalance() {
return balance;
}
public double getInterestRate() {
return interestRate;
}
// mutators
public void setAccountNo(int acctNo) {
this.accountNo = acctNo;
}
public void setBalance(double bal) {
this.balance = bal;
}
public void setInterestRate(double intR) {
this.interestRate = intR;
}
public boolean validateAcctNumber(int search) {
for (int i = 0; i < 100; i++) {
int listVal = getAccountNo();
if (search == listVal) {
return true;
}
}
return false;
}
public void balanceInquiry() {
System.out.print("Enter account number: ");
int search = sc.nextInt();
boolean result = validateAcctNumber(search);
if (result) {
System.out.println("Client name: " + getAccountName());
System.out.println("Balance: " + getBalance());
} else {
System.out.println("Account number invalid!");
}
}
public void deposit() {
System.out.print("Enter account number: ");
int search = sc.nextInt();
boolean result = validateAcctNumber(search);
if (result) {
System.out.print("Enter amount to deposit: ");
double deposit = sc.nextDouble();
if (deposit >= 100) {
balance += deposit;
interestRate = 0.05 * balance;
balance += interestRate;
System.out.println("Amount deposit successful!");
System.out.println("Updated balance: " + balance);
} else {
System.out.println("Invalid deposit number!");
}
} else {
System.out.println("Invalid account number!");
}
}
public void withdraw() {
System.out.print("Enter account number: ");
int search = sc.nextInt();
boolean result = validateAcctNumber(search);
if (result) {
System.out.print("Enter amount to withdraw: ");
double withdraw = sc.nextDouble();
double mainBal = withdraw - balance;
if (withdraw >= 100 && withdraw < balance && mainBal >= 5000) {
balance -= withdraw;
System.out.println("Amount withdrawn successful!");
System.out.println("Updated balance: " + balance);
} else {
System.out.println("Invalid withrawal amount!");
}
} else {
System.out.println("Invalid account number!");
}
}
public void closeAccount() {
System.out.print("Enter account number: ");
int search = sc.nextInt();
boolean result = validateAcctNumber(search);
if (result) {
setAccountNo(0);
setBalance(0);
setAccountName("");
setAddress("");
setBirthday("");
setContactNumber("");
} else {
System.out.println("Invalid account number!");
}
}
}
public class ClientAndaya extends SavingsAccountAndaya {
/**
* #param args the command line arguments
*/
public static void displayMainMenu() {
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");
}
public static void main(String[] args) {
int i = 0;
SavingsAccountAndaya[] sa = new SavingsAccountAndaya[100];
Random rd = new Random();
Scanner sc = new Scanner(System.in);
int input;
do {
displayMainMenu();
System.out.print("Enter number: ");
input = sc.nextInt();
sa[i] = new SavingsAccountAndaya();
switch (input) {
case 1:
System.out.println("New Account: ");
sa[i].getClientDetails();
System.out.print("Enter amount to deposit: ");
double inDepo = sc.nextDouble();
if (inDepo < 5000) {
System.out.println("Invalid initial deposit amount!");
System.out.println("Amount must be greater than 5000 PHP");
System.out.print("Enter amount to deposit: ");
inDepo = sc.nextDouble();
}
sa[i].setBalance(inDepo);
// generate account number
int ranNo = rd.nextInt(9999);
sa[i].setAccountNo(ranNo);
System.out.println("Account number: " + sa[i].getAccountNo());
i++;
break;
case 2:
System.out.println("Balance Inquiry: ");
sa[i].balanceInquiry();
break;
case 3:
System.out.println("Deposit: ");
sa[i].deposit();
break;
case 4:
System.out.println("Withdraw: ");
sa[i].withdraw();
break;
case 5:
System.out.println("Client Profile: ");
System.out.println("Account number: " + sa[i].getAccountNo());
System.out.println("Accoutn Name: " + sa[i].getAccountName());
System.out.println("Address: " + sa[i].getAddress());
System.out.println("Birthday: " + sa[i].getBirthday());
System.out.println("Contact Number: " + sa[i].getContactNumber());
System.out.println("Balance: " + sa[i].getBalance());
break;
case 6:
System.out.println("Close Account: ");
sa[i].closeAccount();
break;
case 7:
break;
default:
System.out.println("Invalid chosen number!");
}
} while (input < 6 && input > 0);
}
}
I can't seem to access or search for an account I've created. Whenever I input the account number, it always results to invalid account number even though I've already created an account that has that account number. I think the problem lies with the validateAcctNumber method:
public boolean validateAcctNumber(int search) {
for (int i = 0; i < 100; i++) {
int listVal = getAccountNo();
if (search == listVal) {
return true;
}
}
return false;
}
It was also mentioned in the instructions to use exception to validate inputs.
How can I solve this problem? Thank you for your help.

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

Bank Account Java Program

I am creating a bank account program for my java class that is suppose to manage up to 5 different bank accounts. The program has to allow the creation of a new account, which I have done, allow deposit and withdraw, which is also done, the 2 parts I cannot get to work are 1: the bank can only have up to 5 accounts, so if a 6th is trying to be created, a message comes up saying that 5 are already created, and 2: one of the options has to print out all the account balances of current accounts in the bank.
This is my code as of now:
import java.util.Scanner;
public class Bankapp {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
Bank myBank = new Bank();
int user_choice = 2;
do {
//display menu to user
//ask user for his choice and validate it (make sure it is between 1 and 6)
System.out.println();
System.out.println("1) Open a new bank account");
System.out.println("2) Deposit to a bank account");
System.out.println("3) Withdraw to bank account");
System.out.println("4) Print account balance");
System.out.println("5) Quit");
System.out.println();
System.out.print("Enter choice [1-5]: ");
user_choice = s.nextInt();
switch (user_choice) {
case 1:
System.out.println("Enter a customer name");
String cn = s.next();
System.out.println("Enter a opening balance");
double d = s.nextDouble();
System.out.println("Account was created and it has the following number: " + myBank.openNewAccount(cn, d));
break;
case 2: System.out.println("Enter a account number");
int an = s.nextInt();
System.out.println("Enter a deposit amount");
double da = s.nextDouble();
myBank.depositTo(an, da);
break;
case 3: System.out.println("Enter a account number");
int acn = s.nextInt();
System.out.println("Enter a withdraw amount");
double wa = s.nextDouble();
myBank.withdrawFrom(acn, wa);
break;
case 4: System.out.println("Enter a account number");
int anum = s.nextInt();
myBank.printAccountInfo(anum);
break;
case 5:
System.out.println("Here are the balances " + "for each account:");
case 6:
System.exit(0);
}
}
while (user_choice != '6');
}
static class Bank {
private BankAccount[] accounts; // all the bank accounts at this bank
private int numOfAccounts = 5; // the number of bank accounts at this bank
// Constructor: A new Bank object initially doesn’t contain any accounts.
public Bank() {
accounts = new BankAccount[5];
numOfAccounts = 0;
}
// Creates a new bank account using the customer name and the opening balance given as parameters
// and returns the account number of this new account. It also adds this account into the account list
// of the Bank calling object.
public int openNewAccount(String customerName, double openingBalance) {
BankAccount b = new BankAccount(customerName, openingBalance);
accounts[numOfAccounts] = b;
numOfAccounts++;
return b.getAccountNum();
}
// Withdraws the given amount from the account whose account number is given. If the account is
// not available at the bank, it should print a message.
public void withdrawFrom(int accountNum, double amount) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
accounts[i].withdraw(amount);
System.out.println("Amount withdrawn successfully");
return;
}
}
System.out.println("Account number not found.");
}
// Deposits the given amount to the account whose account number is given. If the account is not
// available at the bank, it should print a message.
public void depositTo(int accountNum, double amount) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
accounts[i].deposit(amount);
System.out.println("Amount deposited successfully");
return;
}
}
System.out.println("Account number not found.");
}
// Prints the account number, the customer name and the balance of the bank account whose
// account number is given. If the account is not available at the bank, it should print a message.
public void printAccountInfo(int accountNum) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
System.out.println(accounts[i].getAccountInfo());
return;
}
}
System.out.println("Account number not found.");
}
public void printAccountInfo(int accountNum, int n) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
System.out.println(accounts[i].getAccountInfo());
return;
}
}
System.out.println("Account number not found.");
}
}
static class BankAccount{
private int accountNum;
private String customerName;
private double balance;
private static int noOfAccounts=0;
public String getAccountInfo(){
return "Account number: " + accountNum + "\nCustomer Name: " + customerName + "\nBalance:" + balance +"\n";
}
public BankAccount(String abc, double xyz){
customerName = abc;
balance = xyz;
noOfAccounts ++;
accountNum = noOfAccounts;
}
public int getAccountNum(){
return accountNum;
}
public void deposit(double amount){
if (amount<=0) {
System.out.println("Amount to be deposited should be positive");
} else {
balance = balance + amount;
}
}
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;
}
}
}
}//end of class
The program runs fine, I just need to add these two options, and cannot get them to work properly, how would I go about doing this? Also, options 3 and 4 should not work if no accounts have been created yet. Thanks in advance.
UPDATE: this is what I tried, I keep getting a this method must return type int error.
public int openNewAccount(String customerName, double openingBalance) {
if(numOfAccounts > 5)
{
System.out.println("5 accounts already exist");
}
else
{
BankAccount b = new BankAccount(customerName, openingBalance);
accounts[numOfAccounts] = b;
numOfAccounts++;
return b.getAccountNum();
}
}
UPDATE 2: I added a return statement, now when it runs it will open accounts up to number 5, but for every account after number 5 it just says the account number is 5 again instead of not opening an account.
public int openNewAccount(String customerName, double openingBalance) {
if(numOfAccounts > 5)
{
System.out.println("5 accounts already exist");
}
else
{
BankAccount b = new BankAccount(customerName, openingBalance);
accounts[numOfAccounts] = b;
numOfAccounts++;
return b.getAccountNum();
}
return numOfAccounts;
}
Its pretty simple. Create a list of size 5 and add the account into that list when user is created one. Before adding just make a check whether list size <= 5. If it is true, go ahead and add the account, otherwise throw an error
For option 2, just iterate through the list and display the results
1; in the openNewBank account method; before creating the new Bank account and increasing the count by 1; check if the number of account is already at 5 or higher and if it is dont create the account and dont increase the count.
2: Loop through the number of account variable and print.
I added password system to it. and nice looking account num.
Code :
import java.io.*;
import java.util.Random;
public class Computer_Bank_of_India {
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);
int[] arrDetails= myBank.AddNewAccount(Name, Balance);
System.out.println("Account Has been created\n Account number: " + arrDetails[0]+"\nYour password : "+ arrDetails[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];
if (Account_Number == a) {
int p = accounts[i].getAccountNum()[1];
if( pass == p) {
accounts[i].withdraw(Money);
return;
}
}
}
System.out.println(" You have entered a wrong Account number or Password.");
}
public void Deposit(int Account_Number, int pass, double Money) {
for (int i =0; i<numOfAccounts; i++) {
int a = accounts[i].getAccountNum()[0];
if (Account_Number == a) {
int p = accounts[i].getAccountNum()[1];
if( pass == p) {
accounts[i].deposit(Money);
return;
}
}
}
System.out.println(" You have entered a wrong Account number or Password.");
}
public void Transactions(int Account_Number, int pass) {
for(int i = 0;i<numOfAccounts; i++) {
int a = accounts[i].getAccountNum()[0];
if (Account_Number == a ) {
int p = accounts[i].getAccountNum()[1];
if( pass == p) {
System.out.println(accounts[i].getAccountInfo());
System.out.println(" Last transaction: " + accounts[i].getTransactionInfo(accounts[i].getNumberOfTransactions()-1));
return;
}
}
}
System.out.println(" You have entered a wrong Account number or Password.");
}
}
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++;
System.out.println(" Amount deposited successfully");
}
}
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++;
System.out.println(" Amount Withdrawn successfully");
}
}
}
}
}

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

Scanner carriage return Overflow

If anyone can see where I've gone made a mistake in my code I would be eternally grateful. I recognize that it's an obscene amount of code, but I've been pulling my hair out with it over the last few days and simply cannot fathom what to do with it. I've asked others for help in my class but they cannot see where I have gone wrong. It's to do with carriage return scanner problem.
java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at PropertyMenu.runMenu(PropertyMenu.java:109)
at PropertyMenu.main(PropertyMenu.java:7)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at
edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
Any thoughts would be much appreciated.
Joe.
//ROOM CLASS
import java.util.Scanner;
public class Room{
private String description;
private double length;
private double width;
public Room (String description, double length, double width) {
this.description = description;
this.length = length;
this.width = width;
}
public Room(){
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\n");
System.out.println("Enter description of room:");
description = scan.next();
System.out.println("Enter length of room:");
length = scan.nextDouble();
System.out.println("Enter width of room:");
width = scan.nextDouble();
}
public double getArea () {
return length*width;
}
#Override
public String toString() {
String result = ("***********************************\n");
result +=(" Room Viewing \n");
result +=("************************************\n");
result +=("The width of the room is " + width + "m.\n");
result +=("the length of the room is " + length + "m.\n");
result +=("the name of the room is: " + description +".\n");
return result;
}
}
//HOUSE CLASS
import java.util.*;
public class House {
private ArrayList<Room> abode;
private int idNum, numRooms;
private double totalArea;
private static int internalCount = 1;
private String address, roomInfo, houseType;
public House (String address, String houseType, int numRooms){
System.out.println("THIS IS THE START OF MY 3 ARGUMENT CONSTRUCTOR");
idNum = internalCount++;
this.address = address;
this.houseType = houseType;
this.numRooms = numRooms;
System.out.println("THIS IS THE END OF MY 3 ARGUMENT CONSTRUCTOR");
}
public House (String address, String houseType, int numRooms, String roomInfo){
System.out.println("THIS IS THE START OF MY 4 ARGUMENT CONSTRUCTOR");
idNum = internalCount++;
this.address = address;
this.houseType = houseType;
this.numRooms = numRooms;
this.roomInfo = roomInfo;
Scanner scan = new Scanner(roomInfo);
String desc;
Double l;
Double w;
while (scan.hasNext()){
desc= scan.next();
l = Double.parseDouble(scan.next());
System.out.println("the length from here"+l);
w = Double.parseDouble(scan.next());
System.out.println("the width from here"+w);
new Room (desc,l,w);
}
System.out.println("THIS IS THE END OF MY 4 ARGUMENT CONSTRUCTOR");
}
public void addRoom (){
totalArea=0;
abode.add(new Room ());
for (int i=0; i<abode.size(); i++){
totalArea += abode.get(i).getArea();
}
}
public House () {
totalArea = 0;
abode = new ArrayList<Room>();
idNum = ++internalCount;
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\n");
System.out.println("Enter address of house:");
address = scan.next();
System.out.println("Enter number of rooms:");
numRooms = scan.nextInt();
System.out.println("Enter type of house:");
houseType = scan.next();
for (int i=1; i<=numRooms; i++){
addRoom();
}
}
int getIdNum() {
return idNum;
}
#Override
public String toString() {
String result =("************************************\n");
result +=(" House Viewing \n");
result +=("************************************\n");
result +=("The house ID is " + idNum +".\n");
result +=("The house address is " + address +".\n");
result +=("The number of rooms here is " + numRooms +".\n");
result +=("The house type is " + houseType +".\n");
result +=("The total area of the house is " + totalArea +".\n");
result +=(abode);
return result;
}
}
//DRIVER
import java.util.*;
import java.io.*;
public class PropertyMenu {
private ArrayList<House> properties =new ArrayList<House>();
public static void main (String[] args) throws IOException{
PropertyMenu menu = new PropertyMenu();
menu.runMenu();
}
public void runMenu() {
House h = null;
char selection = ' ';
Scanner s = new Scanner(System.in);
while (selection != 'e') {
System.out.println();
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("Welcome to my Property database");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("What do you want to do?");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("To ADD a house enter......A");
System.out.println("To VIEW a house enter.....V");
System.out.println("To DELETE a house enter...D");
System.out.println("To USE a file.............F");
System.out.println("To QUIT enter.............E");
selection = s.next().toLowerCase().charAt(0);
switch (selection) {
case 'a':
properties.add(new House());
break;
case 'v':
System.out.println("Do you want to view all houses (y/n)?");
String all = "";
all = s.next();
if (all.equalsIgnoreCase("y")){
for (int i=0; i<properties.size(); i++){
System.out.println("Property ID: "+ (properties.get(i)));
}
}
else if(all.equalsIgnoreCase("n")){
System.out.println(""+ properties.size() +" houses have been created, choose the id of the house you wish to view.. (1/2/3 etc...)");
System.out.println("List of property ID's: ");
for (int i=0; i<properties.size(); i++){
System.out.println("Property ID: "+ (properties.get(i)).getIdNum());
}
System.out.println("Enter ID of the house you wish to view:");
int viewHouse = s.nextInt();
if (viewHouse <= properties.size() && viewHouse >= 1){
System.out.println(properties.get(viewHouse-1));
}
else{
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(" House Not Present ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
}
}
else{
System.out.println("Do you want to view all houses (y/n)?");
all = s.next();
}
break;
case 'd':
System.out.println(""+ properties.size() +" houses have been created, choose the id of the house you wish to delete.. (1/2/3 etc...)");
System.out.println("List of property ID's: ");
for (int i=0; i<properties.size(); i++){
System.out.println("Property ID: "+ (properties.get(i)).getIdNum());
}
System.out.println("Enter ID of the house you wish to delete:");
int deleteHouse = s.nextInt();
if (deleteHouse <= properties.size() && deleteHouse >= 1){
properties.remove(deleteHouse -1);
}
else{
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(" House Not Present ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
}
break;
case 'e':
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(" Goodbye ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
break;
//*********************************THIS IS WHERE MY PROBLEM IS, FROM HERE*************
case 'f':
try{
Scanner fileScan = new Scanner (new File("property.txt"));
while (fileScan.hasNext()){
System.out.println("THIS IS A FRESH LOOP");
String a;
String ht;
String rms1;
int rms;
String yn;
String rmInfo;
a = fileScan.nextLine();
System.out.println("ADDRESS"+a);
ht = fileScan.nextLine();
System.out.println("HOUSE TYPE"+ht);
rms1 = fileScan.next();
rms = Integer.parseInt(rms1);
System.out.println("HOUSEROOMs"+rms);
yn = fileScan.next();
String overflow = fileScan.nextLine();
System.out.println("Yes/no"+yn);
if (yn.equalsIgnoreCase("Y")){
System.out.println("THIS IS THE START OF CHOICE = Y");
rmInfo = fileScan.nextLine();
properties.add(new House(a, ht, rms, rmInfo));
System.out.println("THIS IS THE END OF CHOICE = Y");
}
else{
System.out.println("THIS IS THE START OF CHOICE = N");
properties.add(new House(a, ht, rms));
System.out.println("THIS IS THE END OF CHOICE = N");
}
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
break;
//******************************************TO HERE^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
default:
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(" Try again! ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
}
}
System.out.println("Exiting program.");
}
}
This is could be a guess that you are not reading file correctly. Whatever I see from your block of file reading code and input file "property.txt" , make following changes.
In your while use following, as you are reading file line by line.
while (fileScan.hasNextLine()){
Only use nextLine() method
rms1 = fileScan.nextLine();
yn = fileScan.nextLine();
I hope these will solve your problem.

Categories

Resources