NullPointException in Simple Program, Cannot Find Fix - java

This is the exception I am getting:
Exception in thread "main" java.lang.NullPointerException
at BankAccountDemo.DisplayAccountFees(BankAccountDemo.java:91)
at BankAccountDemo.main(BankAccountDemo.java:30)
I am also getting this exception whenever I try to print or view all the accounts with the fees assessed.
Here is my driver program. It has 5 classes, which are also below. One of them is an abstract class with 3 descendants.
DRIVER
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
public class BankAccountDemo
{
public static void main(String[] args)
{
while(true) {
Scanner keyboard = new Scanner(System.in);
System.out.println("=========Menu========");
System.out.println("1. Add an account.");
System.out.println("2. To print the names of all accounts together with the fees assessed");
System.out.println("3. To print all accounts together with owner information");
System.out.println("4. To exit program");
System.out.println("Your choice: ");
int input = keyboard.nextInt();
switch(input)
{
case 1:
InputAccount();
break;
case 2:
DisplayAccountFees();
break;
case 3:
ShowAccount();
break;
default:
PrintToFile();
System.exit(0);
}
}
}
private static void InputAccount()
{
System.out.println("Please enter user data as prompted...");
System.out.println("Please enter account type: Press '1' for Checking, '2' for Savings, '3' for Loan");
System.out.println("Account Type: ");
Scanner keyboard = new Scanner(System.in);
int type = keyboard.nextInt();
switch(type)
{
case 1:
{
Checking aChecking = new Checking();
aChecking.AddAccount();
checkAccounts.add(aChecking);
break;
}
case 2:
{
Savings aSavings = new Savings();
aSavings.AddAccount();
savingsAccounts.add(aSavings);
break;
}
case 3:
{
Loan aLoan = new Loan();
aLoan.AddAccount();
loanAccounts.add(aLoan);
break;
}
}
}
private static void DisplayAccountFees()
{
for (int n=0; n < savingsAccounts.size(); n++)
{
Savings aSavings = savingsAccounts.get(n);
Person aPerson = aSavings.getAccountHolder();
System.out.println("Total Fees for: " +aPerson.getPersonName());
System.out.println("with the account number: " +aSavings.getAcctNumber());
System.out.println("are: " + aSavings.accountFee());
}
for (int n=0; n < checkAccounts.size(); n++)
{
Checking aChecking = checkAccounts.get(n);
Person aPerson = aChecking.getAccountHolder();
System.out.println("Total Fees for: " +aPerson.getPersonName());
System.out.println("with the account number: " +aChecking.getAcctNumber());
System.out.println("are: " + aChecking.accountFee());
}
for(int n=0; n < loanAccounts.size(); n++)
{
Loan aLoan = loanAccounts.get(n);
Person aPerson = aLoan.getAccountHolder();
System.out.println("Total Fees for: " +aPerson.getPersonName());
System.out.println("with the account number: " +aLoan.getAcctNumber());
System.out.println("are: " + aLoan.accountFee());
}
}
private static void ShowAccount()
{
for(int n=0; n < savingsAccounts.size(); n++)
{
Savings aSavings = savingsAccounts.get(n);
aSavings.DisplayData();
}
for(int n=0; n < checkAccounts.size(); n++)
{
Checking aChecking = checkAccounts.get(n);
aChecking.DisplayData();
}
for(int n=0; n < loanAccounts.size(); n++)
{
Loan aLoan = loanAccounts.get(n);
aLoan.DisplayData();
}
}
private static void PrintToFile()
{
try
{
FileOutputStream fileOutput = new FileOutputStream("Accounts.dat");
ObjectOutputStream printFile = new ObjectOutputStream(fileOutput);
for (int n=0; n < loanAccounts.size(); n++)
{
Loan aLoan = loanAccounts.get(n);
aLoan.PrintAccountToFile(printFile);
}
for (int n=0; n < checkAccounts.size(); n++)
{
Checking aChecking = checkAccounts.get(n);
aChecking.PrintAccountToFile(printFile);
}
for (int n=0; n < savingsAccounts.size(); n++)
{
Savings aSavings = savingsAccounts.get(n);
aSavings.PrintAccountToFile(printFile);
}
printFile.close();
fileOutput.close();
}
catch(IOException ex)
{
}
}
private static ArrayList<Checking> checkAccounts = new ArrayList<Checking>();
private static ArrayList<Savings> savingsAccounts = new ArrayList<Savings>();
private static ArrayList<Loan> loanAccounts = new ArrayList<Loan>();
}
ACCOUNT CLASS
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Scanner;
public abstract class Account {
private String bankName;
private String bankAddress;
private String acctNumber;
private String acctType;
private double balance;
private Person accountHolder;
public Account()
{
}
public Person setAccountHolder(Person holder)
{
return holder;
}
public void setBankName(String newBankName)
{
bankName = newBankName;
}
public void setAddress(String newBankAddress)
{
bankAddress = newBankAddress;
}
public void setAcctNumber(String newAcctNumber)
{
acctNumber = newAcctNumber;
}
public void setBalance(double newBalance)
{
balance = newBalance;
}
public void setAcctType(String newAcctType)
{
acctType = newAcctType;
}
public Person getAccountHolder()
{
return accountHolder;
}
public String getBankName()
{
return bankName;
}
public String getAddress()
{
return bankAddress;
}
public String getAcctNumber()
{
return acctNumber;
}
public String getAcctType()
{
return acctType;
}
public double getBalance()
{
return balance;
}
public abstract double accountFee();
public abstract void DisplayData();
public abstract void AddAccount();
public abstract void PrintAccountToFile(ObjectOutputStream printFile);
public void readInputAccount()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the name of your bank: ");
bankName = keyboard.nextLine();
System.out.println("Enter the address of your bank: ");
bankAddress = keyboard.nextLine();
System.out.println("Enter your account number: ");
acctNumber = keyboard.nextLine();
System.out.println("Enter your current balance: ");
balance = keyboard.nextDouble();
}
public void PrintBankInfo(ObjectOutputStream printFile)
{
try
{
printFile.writeUTF("------------------------------------------");
printFile.writeUTF(" Bank information: ");
printFile.writeUTF("------------------------------------------");
printFile.writeUTF("Bank name: " + getBankName());
printFile.writeUTF("Bank Address: " + getAddress());
}
catch(IOException ex)
{
}
}
public void DisplayBankInfo()
{
System.out.println("------------------------------------------");
System.out.println(" Bank information: ");
System.out.println("------------------------------------------");
System.out.println("Bank name: " + getBankName());
System.out.println("Bank Address: " + getAddress());
}
}
CHECKING CLASS
import java.util.Scanner;
import java.io.*;
public class Checking extends Account {
private double monthFee;
private int checksAllowed;
private int checksUsed;
public Checking()
{
}
public double accountFee()
{
int tooManyChecks = checksUsed - checksAllowed;
double fee = monthFee + (3.00 * tooManyChecks);
return fee;
}
public double getMonthFee()
{
return monthFee;
}
public int getChecksAllowed()
{
return checksAllowed;
}
public int getChecksUsed()
{
return checksUsed;
}
public void setMonthFee(double newMonthFee)
{
monthFee = newMonthFee;
}
public void setChecksAllowed(int newChecksAllowed)
{
checksAllowed = newChecksAllowed;
}
public void setChecksUsed(int newChecksUsed)
{
checksUsed = newChecksUsed;
}
public void AddAccount()
{
Person aPerson = new Person();
aPerson.personInput();
setAccountHolder(aPerson);
readInputAccount();
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the monthly fee: ");
monthFee = keyboard.nextDouble();
System.out.println("Please enter the number of free checks allowed: ");
checksAllowed = keyboard.nextInt();
System.out.println("Please enter the number of checks used: ");
checksUsed = keyboard.nextInt();
}
public void DisplayData()
{
Person aPerson = getAccountHolder();
aPerson.DisplayPersonInfo();
DisplayBankInfo();
System.out.println("------------------------------------------");
System.out.println(" Account information: ");
System.out.println("Account Type : Checking");
System.out.println("Bank account number :" + getAcctNumber());
System.out.println("Account balance :" + getBalance());
System.out.println("Monthly fee :" + getMonthFee());
System.out.println("Number of checks used :" + getChecksUsed());
System.out.println("Number of free checks :" + getChecksAllowed());
}
public void PrintAccountToFile(ObjectOutputStream printFile)
{
try
{
Person aPerson = getAccountHolder();
aPerson.PrintInfo(printFile);
PrintBankInfo(printFile);
printFile.writeUTF("------------------------------------------");
printFile.writeUTF(" Account information: ");
printFile.writeUTF("Account Type : Checking");
printFile.writeUTF("Bank account number :" + getAcctNumber());
printFile.writeUTF("Account balance :" + getBalance());
printFile.writeUTF("Monthly fee :" + getMonthFee());
printFile.writeUTF("Number of checks used :" + getChecksUsed());
printFile.writeUTF("Number of free checks :" + getChecksAllowed());
printFile.writeUTF("Fees accessed : " + accountFee());
}
catch(IOException ex)
{
}
}
}
LOAN CLASS
import java.util.Scanner;
import java.io.*;
public class Loan extends Account {
private double monthPayment;
private int daysOverDue;
public Loan()
{
}
public void setMonthPayment(double newMonthPayment)
{
monthPayment = newMonthPayment;
}
public void setDaysOverDue(int newDaysOverDue)
{
daysOverDue = newDaysOverDue;
}
public double getMonthPayment()
{
return monthPayment;
}
public int getDaysOverDue()
{
return daysOverDue;
}
public double accountFee()
{
double fee = 0.001 * monthPayment * daysOverDue;
return fee;
}
public void AddAccount(){
Scanner keyboard = new Scanner(System.in);
Person aPerson = new Person();
aPerson.personInput();
setAccountHolder(aPerson);
readInputAccount();
System.out.println("Please enter the monthly payment amount: ");
monthPayment = keyboard.nextDouble();
System.out.println("Please enter the number of days past the grace period: ");
daysOverDue = keyboard.nextInt();
}
public void DisplayData()
{
Person aPerson = getAccountHolder();
aPerson.DisplayPersonInfo();
}
public void PrintAccountToFile(ObjectOutputStream printFile)
{
try
{
Person aPerson = getAccountHolder();
aPerson.PrintInfo(printFile);
printFile.writeUTF("------------------------------------------");
printFile.writeUTF(" Account information: ");
printFile.writeUTF("Account Type: Loan");
printFile.writeUTF("Bank account number: " + getAcctNumber());
printFile.writeUTF("Account balance: " + getBalance());
printFile.writeUTF("Monthly payment amount: " + getMonthPayment());
printFile.writeUTF("Number of days past the grace period: " + getDaysOverDue());
printFile.writeUTF("Fees assessed: " + accountFee());
}
catch(IOException ex)
{
}
}
}
SAVINGS CLASS
import java.io.*;
import java.util.Scanner;
public class Savings extends Account {
private double minBal;
private double intRate;
private double avgBal;
public Savings()
{
}
public double accountFee()
{
double fee = 0.00;
if (avgBal < minBal)
{
fee = 50.00;
}
return fee;
}
public double getMinBal()
{
return minBal;
}
public double getIntRate()
{
return minBal;
}
public double getAvgBal()
{
return avgBal;
}
public void setMinBal(double newMinBal)
{
minBal = newMinBal;
}
public void setIntRate(double newIntRate)
{
minBal = newIntRate;
}
public double getChecks()
{
return intRate;
}
public void setChecks(double newIntRate)
{
intRate = newIntRate;
}
public void setAvgBal(double newAvgBal)
{
avgBal = newAvgBal;
}
public void AddAccount()
{
Scanner keyboard = new Scanner(System.in);
Person aPerson = new Person();
aPerson.personInput();
setAccountHolder(aPerson);
readInputAccount();
System.out.println("Please enter the minimum balance: ");
minBal = keyboard.nextDouble();
System.out.println("Please enter the average balance: ");
avgBal = keyboard.nextDouble();
System.out.println("Please enter interest rate");
intRate = keyboard.nextDouble();
}
public void DisplayData()
{
Person aPerson = getAccountHolder();
aPerson.DisplayPersonInfo();
DisplayBankInfo();
System.out.println("------------------------------------------");
System.out.println(" Account information: ");
System.out.println("Account Type: Savings Account");
System.out.println("Bank account number: " + getAcctNumber());
System.out.println("Account balance: " + getBalance());
System.out.println("Minimum balance: " + getMinBal());
System.out.println("Average balance: " + getAvgBal());
System.out.println("Interest rate: " + getIntRate());
}
public void PrintAccountToFile(ObjectOutputStream printFile)
{
try
{
Person aPerson = getAccountHolder();
aPerson.PrintInfo(printFile);
PrintBankInfo(printFile);
printFile.writeUTF("------------------------------------------");
printFile.writeUTF(" Account information: ");
printFile.writeUTF("Account Type: Savings Account");
printFile.writeUTF("Bank account number: " + getAcctNumber());
printFile.writeUTF("Account balance: " + getBalance());
printFile.writeUTF("Minimum balance: " + getMinBal());
printFile.writeUTF("Average balance: " + getAvgBal());
printFile.writeUTF("Interest rate: " + getIntRate());
printFile.writeUTF("Fees assessed: " + accountFee());
}
catch(IOException ex)
{
}
}
}

The problem is that your setAccountHolder method doesn't actually set anything:
Instead of:
public Person setAccountHolder(Person holder)
{
return holder;
}
it should be:
public void setAccountHolder(Person holder) {
this.accountHolder = holder;
}

1.) Where do you initialize savingsAccounts attribute?
2.) When you do
DisplayAccountFees()
you start by doing
Savings aSavings = savingsAccounts.get(n);
are you sure that get(n) always returns data?

Related

How to check if input meets the criteria?

Part of my assignment was to have the user input an Eployee Id between 0-9 and contains a letter between A-M(ex. 999-M), and then if it doesn't meet one of the criteria it is supposed to throw an error code using an exception class. I figured out how to check the Id, but only works with the number part. I have no clue how to check if the input also meets the letter criteria. I know it has something to do with employee Id being an int and not a string, but when I attempted to fix it. I almost messed my whole code up. Any help would be appreciated.
My main code:
package payrollexceptions;
import java.util.Scanner;
public class PayRollExceptions
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
Payroll employee = new Payroll();
String name;
int employeeId;
double payRate;
System.out.print("Enter the employee's name: ");
employee.setName(keyboard.nextLine());
System.out.print("Enter employee number, (ex. 999-M): ");
employee.setEmployeeId(keyboard.nextInt());
System.out.print("Enter the employee's hourly rate: ");
employee.setPayRate(keyboard.nextDouble());
System.out.print("Enter the number of hours the employee has worked: ");
employee.setHours(keyboard.nextInt());
System.out.println("\n" + employee.getName());
System.out.println("-----------");
System.out.println("ID: " + employee.getEmployeeId());
System.out.println("Pay rate: $" + employee.getPayRate());
System.out.println("Hours worked: $" + employee.getHours());
System.out.println("Gross pay: $" + employee.getGrossPay());
}
}
The code that involves setting the employeeId:
package payrollexceptions;
public class Payroll
{
private int employeeId, hours;
private double payRate;
private String name;
public Payroll() {}
public Payroll(String name, int employeeId, double payRate)
{
try
{
if(name == "")
{
throw new EmptyNameException();
}
setName(name);
if(employeeId <= 0)
{
throw new InvalidEmployeeIdException();
}
setEmployeeId(employeeId);
if(payRate < 0 || payRate > 25)
{
throw new InvalidPayRateException();
}
setPayRate(payRate);
}
catch(EmptyNameException e)
{
System.out.println("Error: the employee's name cannot be blank");
System.exit(1);
}
catch(InvalidEmployeeIdException e)
{
System.out.println("Error: the employee's id must be above 0");
System.exit(1);
}
catch(InvalidPayRateException e)
{
System.out.println("Error: the payrate must not be negative nor exceed 25");
System.exit(1);
}
setEmployeeId(employeeId);
setPayRate(payRate);
}
public double getGrossPay()
{
return payRate * hours;
}
public int getEmployeeId()
{
return employeeId;
}
public int getHours()
{
return hours;
}
public double getPayRate()
{
return payRate;
}
public String getName()
{
return name;
}
public void setEmployeeId(int employeeId)
{
try
{
if(employeeId <= 0)
{
throw new InvalidEmployeeIdException();
}
this.employeeId = employeeId;
}
catch(InvalidEmployeeIdException e)
{
System.out.println("Error: Numericals in ID must be between 0-9 and letters must be between A-M");
System.exit(1);
}
}
public void setHours(int hours)
{
try
{
if(hours < 0 || hours > 84)
{
throw new InvalidHoursException();
}
this.hours = hours;
}
catch(InvalidHoursException e)
{
System.out.println("Error: Hours Cannot be negative or greater than 84");
System.exit(1);
}
}
public void setPayRate(double payRate)
{
try
{
if(payRate < 0 || payRate > 25)
{
throw new InvalidPayRateException();
}
this.payRate = payRate;
}
catch(InvalidPayRateException e)
{
System.err.println("Error: Hourly Rate Cannot be negative or greater than 25");
System.exit(1);
}
}
public void setName(String name)
{
try
{
if(name.isEmpty())
{
throw new EmptyNameException();
}
this.name = name;
}
catch(EmptyNameException e)
{
System.out.println("Error: the employee's name cannot be blank");
System.exit(1);
}
}
}

How to write tests for my static methods?

In the Fileoperator class I tried to make a couple methods to enable saving (from inputs from the screen to a text file) and loading (from exactly the same text file and print it out on screen). Since both of them are static methods, I can't quote them directly in my FileoperatorTest. How could I write the tests for them?
(I've already written some tests for Person.)
public class Fileoperator {
private ArrayList<Person> saveList;
private Scanner scanner;
int age;
String name;
int income;
int expenditure;
int willingnesstoInvest;
String exit;
public Fileoperator() {
saveList = new ArrayList<>();
scanner = new Scanner(System.in);
processOperations();
}
private void processOperations() {
while (true) {
Person personEntry = getPerson();
if (exit.equals("yes")) {
personEntry.updateMaster(age, name, income, expenditure, willingnesstoInvest);
personResult(personEntry);
break;
}
personEntry.updateMaster(age, name, income, expenditure, willingnesstoInvest);
personResult(personEntry);
System.out.println(personEntry.print());
}
for (Person p: saveList) {
System.out.println(p.print());
}
}
private Person getPerson() {
Person personEntry = new Person(0, "", 0, 0, 0);
System.out.println("Age: ");
age = scanner.nextInt();
scanner.nextLine();
System.out.println("Name: ");
name = scanner.nextLine();
System.out.println("Income: ");
income = scanner.nextInt();
System.out.println("Expenditure:");
expenditure = scanner.nextInt();
System.out.println("Willingness to invest: ");
willingnesstoInvest = scanner.nextInt();
scanner.nextLine();
System.out.println("done?(yes or no)");
exit = scanner.nextLine();
return personEntry;
}
private void personResult(Person p) {
saveList.add(p);
}
public static void mainhelper() {
try {
printload(load());
} catch (IOException e) {
e.printStackTrace();
}
Fileoperator fo = new Fileoperator();
try {
fo.save();
} catch (IOException e) {
e.printStackTrace();
}
}
public void save() throws IOException {
List<String> lines = Files.readAllLines(Paths.get("output.txt"));;
PrintWriter writer = new PrintWriter("output.txt","UTF-8");
for (Person p: saveList) {
lines.add(p.getAge() + ", " + p.getName() + ", "
+ p.getIncome() + ", " + p.getExpenditure() + ", " + p.getwillingnesstoInvest());
}
for (String line : lines) {
ArrayList<String> partsOfLine = splitOnSpace(line);
System.out.println("Age: " + partsOfLine.get(0) + ", ");
System.out.println("Name: " + partsOfLine.get(1) + ", ");
System.out.println("Income " + partsOfLine.get(2) + ", ");
System.out.println("Expenditure " + partsOfLine.get(3) + ", ");
System.out.println("WillingnesstoInvest " + partsOfLine.get(4) + ", ");
writer.println(line);
}
writer.close(); //note -- if you miss this, the file will not be written at all.
}
public static ArrayList<String> splitOnSpace(String line) {
String[] splits = line.split(", ");
return new ArrayList<>(Arrays.asList(splits));
}
public static ArrayList<Person> load() throws IOException {
List<String> lines = Files.readAllLines(Paths.get("output.txt"));
ArrayList<Person> loadList = new ArrayList();
for (String line : lines) {
if (line.equals("")) {
break;
} else {
Person fromline = fromline(line);
loadList.add(fromline);
}
}
return loadList;
}
public static void printload(ArrayList<Person> loadList) {
for (Person p: loadList) {
System.out.println(p.print());
}
}
private static Person fromline(String line) {
Person fromline = new Person(0, "", 0, 0, 0);
ArrayList<String> partsOfLine = splitOnSpace(line);
int age = Integer.parseInt(partsOfLine.get(0));
int income = Integer.parseInt(partsOfLine.get(2));
int expenditure = Integer.parseInt(partsOfLine.get(3));
int willingnesstoInvest = Integer.parseInt(partsOfLine.get(4));
fromline.updateMaster(age, partsOfLine.get(1), income, expenditure, willingnesstoInvest);
return fromline;
}
}

Java Obtaining the First Element and Then Removing that First Element Printing the Rest of the Elements

Here is my code:
import java.util.LinkedList;
import java.util.Scanner;
import java.util.InputMismatchException;
import java.util.*;
class Customer {
public String lastName;
public String firstName;
public Customer() {
}
public Customer(String last, String first) {
this.lastName = last;
this.firstName = first;
}
public String toString() {
return firstName + " " + lastName;
}
}
class HourlyCustomer extends Customer {
public double hourlyRate;
public HourlyCustomer(String last, String first) {
super(last, first);
}
}
class GenQueue<E> {
private LinkedList<E> list = new LinkedList<E>();
public void enqueue(E item) {
list.addLast(item);
}
public E dequeue() {
return list.poll();
}
public boolean hasItems() {
return !list.isEmpty();
}
public boolean isEmpty()
{
return list == null;
}
public E removeFirst(){
return list.removeFirst();
}
public E getFirst(){
return list.getFirst();
}
public int size() {
return list.size();
}
public void addItems(GenQueue<? extends E> q) {
while (q.hasItems()) list.addLast(q.dequeue());
}
}
public class something {
public static void main(String[] args){
while(true){
Scanner sc = new Scanner(System.in);
String input1;
String input2;
int choice = 1000;
GenQueue<Customer> empList;
empList = new GenQueue<Customer>();
GenQueue<HourlyCustomer> hList;
hList = new GenQueue<HourlyCustomer>();
do{
System.out.println("================");
System.out.println("Queue Operations Menu");
System.out.println("================");
System.out.println("1,Enquene");
System.out.println("2,Dequeue");
System.out.println("0, Quit\n");
System.out.println("Enter Choice:");
try{
choice = sc.nextInt();
switch(choice){
case 1:
do{
System.out.println("\nPlease enter last name: ");
input1 = sc.next();
System.out.println("\nPlease enter first name: ");
input2 = sc.next();
hList.enqueue(new HourlyCustomer(input1, input2));
empList.addItems(hList);
System.out.println("\n"+(input2 + " " + input1) + " is successful queued");
System.out.println("\nDo you still want to enqueue?<1> or do you want to view all in queue?<0> or \nBack to main menu for dequeueing?<menu>: ");
choice = sc.nextInt();
}while (choice != 0);
System.out.println("\nThe customers' names are: \n");
while (empList.hasItems()) {
Customer emp = empList.dequeue();
System.out.println(emp.firstName + " " + emp.lastName + "\n" );
}
// int choose;
// do{
//
//
// System.out.println("\nGo back to main?<1=Yes/0=No>: \n");
// choose = sc.nextInt();
// }while (choose != 1);
break;
case 2:
if (empList.isEmpty()) {
System.out.println("The queue is empty!");
}
else{
System.out.println("\nDequeued customer: " +empList.getFirst());
empList.removeFirst();
System.out.println("\nNext customer in queue: " +empList.getFirst()+"\n");
}
break;
case 0:
System.exit(0);
default:
System.out.println("Invalid choice");
}
}
catch(InputMismatchException e){
System.out.println("Please enter 1-5, 0 to quit");
sc.nextLine();
}
}while(choice != 0);
}
}
}
Case 2 shows no error but when I run it on the IDE it shows:
Exception in thread "main" java.util.NoSuchElementException at
java.util.LinkedList.getFirst(Unknown Source) at
GenQueue.getFirst(something.java:44) at
something.main(something.java:113)
Any idea why this happen? and how to fix it? Your help will be very much appreciated, from python I just went Java today, newbie here.
NoSuchElementException is thrown by LinkedList.getFirst when the list is empty.
You should handle that particular case before calling that method, for example:
if (!empList.hasItems()) {
System.out.println("The queue is empty!");
} else {
System.out.println("First in queue: " +empList.getFirst());
... // rest of code
}

Queues and Stacks Hiring and Firing

I finished this program and demo for my TA. I completely forgot one thing. So, the program is about hiring and firing people using stack and queues. I figured everything out except for one thing. I have to hire at least 3 people and whoever the first applicant is, I will hire them first so on. Here's the problem:
When I fire someone (The last person hired), that person should be the next person to get hired. Example:
Fired Name: b SS: 2
next person hired should be
Hired Name: b SS: 2.
I can't figure out how to get the last person fired to be the next person hired. Here's my program:
class Person {
public String name;
public String SS;
public Person(String N, String S) {
this.name = N;
this.SS = S;
}
}
class Manager {
Scanner keyboard = new Scanner(System.in);
private Queue<Person> app = new Queue<Person>();
public Stack<Person> hire = new Stack<Person>();
public Stack<Person> fire = new Stack<Person>();
public void Apply() throws QueueException {
System.out.print("Applicant Name: ");
String appName = keyboard.nextLine();
System.out.print("SSN: ");
String appSS = keyboard.nextLine();
Person apply = new Person(appName, appSS);
app.enqueue(apply);
}
public void hire() throws QueueException {
if (!app.isEmpty()) {
Person newHire = hire.push(app.dequeue());
System.out.println("Hired \nName: " + newHire.name + " SS: " + newHire.SS);
//hire.push(app.dequeue());
} else if (!fire.isEmpty()) {
Person newFire = app.dequeue();
System.out.println("Hired \nName: " + newFire.name + " SS: " + newFire.SS);
} else {
System.out.println("Nobody to hire.");
}
}
public void fire() throws StackException {
if (!hire.isEmpty()) {
Person newFire = fire.push(hire.pop());
System.out.println("Fired \nName: " + newFire.name + " SS: " + newFire.SS);
fire.push(hire.pop());
} else {
System.out.println("Nobody to fire");
}
}
}
public class Management {
public static void main(String[] args) throws QueueException, StackException {
Scanner keyboard = new Scanner(System.in);
Manager user = new Manager();
boolean test = true;
while (test) {
System.out.print("Press \n\t1 ACCEPT APPLICANT");
System.out.print("\n\t2 Hire \n\t3 Fire \n\t4 Quit:");
System.out.print("\nAnswer: \n");
int action = keyboard.nextInt();
String space = keyboard.nextLine();
if (action == 1) {
user.Apply();
} else if (action == 2) {
user.hire();
} else if (action == 3) {
user.fire();
} else if (action == 4) {
System.exit(0);
} else {
System.out.println("Please try again.");
}
}
you have this error on the hire() method.
Person newFire = app.dequeue();
you see that you are executing this line even tho app queue is Empty. just use fire stack instead of app queue.
public void hire() throws QueueException {
if (!app.isEmpty()) {
Person newHire = hire.push(app.dequeue());
System.out.println("Hired \nName: " + newHire.name + " SS: " + newHire.SS);
//hire.push(app.dequeue());
} else if (!fire.isEmpty()) {
Person newFire = fire.pop();
hire.push(newFire);
System.out.println("Hired \nName: " + newFire.name + " SS: " + newFire.SS);
} else {
System.out.println("Nobody to hire.");
}
}

Element update for Java Util List [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have an ArrayList for Patients in little hospital system and need to write a method to update the patient information. This method should take an integer called "id", match this id with all id's in Patient ArrayList and change some information in that object. How can I iterate this list? Thanks.
This is my Patient Class
import java.util.ArrayList;
import java.util.List;
public class Patient {
String strName,strSurname,strAddress,strDepartment,strGender;
int iId,iClass,iDob;
List<Entry> entries = new ArrayList<Entry>();
long longTel;
boolean boolAllergy,boolChronicDisease,boolRegularMedicine;
public boolean isBoolAllergy() {
return boolAllergy;
}
public void setBoolAllergy(boolean boolAllergy) {
this.boolAllergy = boolAllergy;
}
public boolean isBoolChronicDisease() {
return boolChronicDisease;
}
public void setBoolChronicDisease(boolean boolChronicDisease) {
this.boolChronicDisease = boolChronicDisease;
}
public boolean isBoolRegularMedicine() {
return boolRegularMedicine;
}
public void setBoolRegularMedicine(boolean boolRegularMedicine) {
this.boolRegularMedicine = boolRegularMedicine;
}
public String getStrName() {
return strName;
}
public void setStrName(String strName) {
this.strName = strName;
}
public String getStrSurname() {
return strSurname;
}
public void setStrSurname(String strSurname) {
this.strSurname = strSurname;
}
public String getStrAddress() {
return strAddress;
}
public void setStrAddress(String strAddress) {
this.strAddress = strAddress;
}
public String getStrDepartment() {
return strDepartment;
}
public void setStrDepartment(String strDepartment) {
this.strDepartment = strDepartment;
}
public int getiId() {
return iId;
}
public void setiId(int iId) {
this.iId = iId;
}
public long getlongTel() {
return longTel;
}
public void setiTel(long iTel) {
this.longTel = iTel;
}
public int getiClass() {
return iClass;
}
public void setiClass(int iClass) {
this.iClass = iClass;
}
public int getiDob() {
return iDob;
}
public void setiDob(int iDob) {
this.iDob = iDob;
}
public String getStrGender() {
return strGender;
}
public void setStrGender(String strGender) {
this.strGender = strGender;
}
public void Details() {
System.out.println("*********************************");
System.out.println("Patient Id: " + getiId());
System.out.println("Name: " + getStrName() + " Surname: " + getStrSurname());
System.out.println("Address: " + getStrAddress() + " Department: " + getStrDepartment() + " Gender: " + getStrGender());
System.out.println("Class: " + getiClass() + " Date of birth: " + getiDob() + " Tel: " + getlongTel());
System.out.println("Chronical Disease? " + isBoolChronicDisease());
System.out.println("Any Allergy? " + isBoolAllergy());
System.out.println("Using regular drugs?" + isBoolRegularMedicine());
System.out.println("*********************************");
}
}
And this is the main class that uses Patient class
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
public class Main {
static List<Doctor> listDoctors = new ArrayList<Doctor>();
static List<Nurse> listNurses = new ArrayList<Nurse>();
static List<Patient> listPatients = new ArrayList<Patient>();
static String strUserName = "admin";
static String strPass = "password";
public static void main(String[] args) {
#SuppressWarnings("unused")
int iChoice;
boolean exit = false;
boolean boolAccess = Login();
if (boolAccess) {
while(!exit) {
iChoice = Menu();
switch(iChoice) {
case 1:
AddDoctor();
break;
case 2:
AddNurse();
break;
case 3:
AddPatient();
break;
case 4:
ListDoctors();
break;
case 5:
ListNurses();
break;
case 6:
ListPatients();
break;
case 8:
ChangeUserName();
break;
case 9:
ChangePass();
break;
//Hastalığa göre hastalar listelenecek
//Kronik hastlalıkları olan hastalar listelenecek
//Sigortasını yatırmayan hastalar listelenecek
//delete ve update olayları
//Hastaneye sevkedilen hastalar listelenecek
//Yatılı kalan hastalar listelensin
//Raporlu olan entryler listelenecek
//Kayıt girilirken eğer hasta ismi ilk defa giriliyorsa önce hasta kaydı yapın diye uyarı cıkacak
case 15:
exit = true;
break;
}
}
}
}
private static void ChangeUserName() {
Scanner scan = new Scanner(System.in);
if(Login()) {
System.out.println("Enter new User Name:");
strUserName = scan.next();
System.out.println("Saved..");
}
}
private static void ChangePass() {
Scanner scan = new Scanner(System.in);
if(Login()) {
System.out.println("Enter new Password:");
strPass = scan.next();
System.out.println("Saved..");
}
}
private static void ListNurses() {
Iterator<Nurse> it = listNurses.iterator();
while(it.hasNext()) {
Nurse nur = (Nurse) it.next();
nur.Details();
}
}
private static void ListPatients() {
Iterator<Patient> it = listPatients.iterator();
while(it.hasNext()) {
Patient patient = (Patient) it.next();
patient.Details();
}
}
public static boolean Login() {
Scanner scan = new Scanner(System.in);
System.out.println("Enter Username: ");
if(strUserName.contentEquals(scan.next())) {
System.out.println("Enter Password:");
if(strPass.contentEquals(scan.next())) {
return true;
}
else
System.out.println("Wrong password");
return Login();
}
System.out.println("Wrong user name");
return Login();
}
public static int Menu() {
Scanner scan = new Scanner(System.in);
System.out.println("Choose one of the following order:");
System.out.println("1.Enter new Doctor");
System.out.println("2.Enter new Nurse");
System.out.println("3.Enter new Patient");
System.out.println("4.List all doctors");
System.out.println("5.List all nurses");
System.out.println("6.List all patients");
System.out.println("8.Change user name");
System.out.println("9.Change password");
System.out.println("15.Exit");
return scan.nextInt();
}
private static void ListDoctors() {
Iterator<Doctor> it = listDoctors.iterator();
while(it.hasNext()) {
Doctor doc = (Doctor) it.next();
doc.Details();
}
}
private static void AddDoctor() {
Doctor doctor;
String strName,strSurname,strSpeciality;
int iSSN;
Scanner scan = new Scanner(System.in);
System.out.println("Enter name:");
strName=scan.next();
System.out.println("Enter surname:");
strSurname = scan.next();
System.out.println("Enter speciality");
strSpeciality = scan.next();
System.out.println("Enter SSN");
iSSN = scan.nextInt();
doctor = new Doctor(strName,strSurname,strSpeciality,iSSN);
listDoctors.add(doctor);
System.out.println("Saved..");
}
private static void AddNurse() {
Nurse nurse;
String strName,strSurname;
int iSSN;
Scanner scan = new Scanner(System.in);
System.out.println("Enter name:");
strName=scan.next();
System.out.println("Enter surname:");
strSurname = scan.next();
System.out.println("Enter SSN");
iSSN = scan.nextInt();
nurse = new Nurse(strName,strSurname,iSSN);
listNurses.add(nurse);
System.out.println("Saved..");
}
private static void AddPatient() {
Patient patient = new Patient();
Scanner scan = new Scanner(System.in);
System.out.println("Enter name:");
patient.setStrName(scan.next());
System.out.println("Enter surname:");
patient.setStrSurname(scan.next());
System.out.println("Enter date of birth(DDMMYYYY)");
patient.setiDob(scan.nextInt());
System.out.println("Enter address:");
patient.setStrAddress(scan.next());
System.out.println("Enter department:");
patient.setStrDepartment(scan.next());
System.out.println("Enter gender:");
patient.setStrGender(scan.next());
System.out.println("Enter Telephone number:");
patient.setiTel(scan.nextLong());
System.out.println("Enter id:");
patient.setiId(scan.nextInt());
System.out.println("Enter class:");
patient.setiClass(scan.nextInt());
System.out.println("Does patient have any chronical disease? (Y/N)");
if(scan.next().contentEquals("Y"))
patient.setBoolChronicDisease(true);
else
patient.setBoolChronicDisease(false);
System.out.println("Does patient use any regular drugs? (Y/N)");
if(scan.next().contentEquals("Y"))
patient.setBoolRegularMedicine(true);
else
patient.setBoolRegularMedicine(false);
System.out.println("Does patient have any allergies?");
if(scan.next().contentEquals("Y"))
patient.setBoolAllergy(true);
else
patient.setBoolAllergy(false);
listPatients.add(patient);
}
private static void SearchPatientById(int id) {
Iterator<Patient> it = listPatients.iterator();
while(it.hasNext()) {
Patient patient = (Patient) it.next();
if(it.next().getiId() == id)
patient.Details();
}
}
}
With a slight modification your searchPatientById can return the found patient object:
private static Patient searchPatientById(int id) {
Iterator<Patient> it = listPatients.iterator();
while(it.hasNext()) {
Patient patient = (Patient) it.next();
if(patient.getiId() == id)
return patient;
}
// if not found return null
return null;
}
Note that I remove your double call to next()
That way, you can do something like
Patient foundPatient = searchPatientById(idToFind);
if (foundPatient != null) {
foundPatient.setBoolAllergy(patientsAllergyState);
} else {
// whatever you need to do if the patient cannot be found
}
Also note that in Java it's not common to encode the variable type into the variable names, but there's a universally followed naming convention

Categories

Resources