I have following classes in the project:
Account
Customer
Name: fName and lName (both are String fields)
Date: year, month, day (all are int fields)
Bank: contains collection of accounts
InputReader: reads the input from the keyboard
An Account object requires a Customer object and an opening balance.
A Customer object requires a Name object and a Date object.
A Name object requires Strings for first and last names
I need to ask the user for the details to create the Name and Date objects, and also the opening balance.
I have to create a new Account by getting the relevant information from the user, i.e. it asks the user to type in the customer's name, date of birth etc. It reads in the user responses, creates the account and adds it to the bank.
I keep getting an error message saying "java.lang.NullPointerException" when I run the public void createNewAccount() method. Would appreciate any help. Thanks in advance.
Below is my source code for the Bank class.
import java.util.ArrayList;
public class Bank
{
public static final double INTEREST_RATE = 0.012;//1.2%
// instance variables - replace the example below with your own
private ArrayList<Account> accounts;
private InputReader reader;
private Name fullName;
private Date dateOfBirth;
/**
* Constructor for objects of class Bank
*/
public Bank()
{
// initialise instance variables
}
/*
* Adds an existing Account to the bank
* #param account
*/
public void addAccount(Account account)
{
accounts.add(account);
}
public void createNewAccount() {
System.out.println("Please enter your first name: ");
String firstName = reader.readString();
System.out.println("Hello " + firstName + ". " + "What is your last name?");
String lastName = reader.readString();
System.out.println("Your last name is " + lastName);
System.out.println("Please enter your year of birth: ");
int thisYear = reader.readInt();
System.out.println("Please enter your month of birth: ");
int thisMonth = reader.readInt();
System.out.println("Please enter your date of birth: ");
int thisDay = reader.readInt();
Name theName = new Name(firstName, lastName);
Date theDateOfBirth = new Date(thisYear, thisMonth, thisDay);
}
}
You have to initialize reader before you can attempt to read from it.
You can change reader with Scanner. Something like that.
Scanner scan = new Scanner(System.in);
System.out.println("Please enter your first name: ");
String firstName = scan.next();
System.out.println("Hello " + firstName + ". " + "What is your last name?");
String lastName = scan.next();
System.out.println("Your last name is " + lastName);
System.out.println("Please enter your year of birth: ");
int thisYear = scan.nextInt();
System.out.println("Please enter your month of birth: ");
int thisMonth = scan.nextInt();
System.out.println("Please enter your date of birth: ");
int thisDay = scan.nextInt();
//Then do what you are supposed to do......
Scanner scanner = new Scanner(System.in);
The scanner object has a lot of functions you can use;
Your InputReader reader is declared, but not initialised, hence NullPointerExceptin. Change it to more commonly used:
Scanner scanner = new Scanner(System.in);
Then you can use it's methods for user input:
scanner.nextLine() for strings
scanner.nextInt() for ints
scanner.nextDouble() for doubles
etc.
Check the docs here.
You need to initialize your instance variables:
public class Bank
{
public static final double INTEREST_RATE = 0.012;
private ArrayList<Account> accounts;
private InputReader reader;
private Name fullName;
private Date dateOfBirth;
public Bank()
{
// initialise instance variables <- where it says to
accounts = new ArrayList<Account>();
reader = new InputReader();
...
}
InputReader must be part of the assignment package so I don't know what its constructor properly is.
Related
I'm currently learning java and starting on methods, classes and objects. I'm attempting to code a simple program to have set values for 2 separate employee's at a company that would then allow for user input to alter certain variables of a specific object. The variables needing to be updated via user input will be the MonthlySalary and FirstName of the object employee2. I'm not really sure how to structure the user input part and I'm at a loss trying to find a solution.
import java.util.Scanner;
public class EmployeeTest
{
public static void main( String[] args ){
Scanner input = new Scanner(System.in);
// Create 2 Employee objects
Employee employee1 = new Employee( "Jane", "Doe", 5000 );
Employee employee2 = new Employee( "John", "Bloggs", 4500 );
// Do other steps (not requiring input)
// Ask for user input of Employee 2's new first name
System.out.println( "Please enter new first name for Employee 2: \n");
String input = employee2.newFirstName();
// repeat above to set Employee 2's new salary then display new information
}
}
With the Class file Employee.java
public class Employee
{
private String firstName; // Employee's First Name
private String lastName; // Employee's Last Name
private double monthlySalary; // Employee's Monthly Salary
// Employee constructor
public Employee( String initFirstName, String initLastName, double initMonthlySalary )
{
firstName = initFirstName;
lastName = initLastName;
if (initMonthlySalary > 0)
monthlySalary = initMonthlySalary;
else
monthlySalary = 0;
}
public Employee( )
{
firstName = "";
lastName = "";
monthlySalary = 0;
}
// Method to assign the employee's First Name
public void setFirstName( String newFirstName )
{
firstName = newFirstName;
}
// Method to assign the employee's Monthly Salary
public void setMonthlySalary( double newMonthlySalary )
{
if (newMonthlySalary > 0) monthlySalary = newMonthlySalary;
}
// Other required methods
}
You are struggling to take input from the console.
System.out.println("Please enter new first name for Employee 2: ");
String firstName = input.next();
employee2.setFirstName(firstName);
System.out.println("Please enter new Salary for Employee 2: ");
double salary = input.nextDouble();
employee2.setMonthlySalary(salary);
This will work for you. And please go through the basic syntaxes first. Because otherwise you are wasting your own time banging your head for this kind of syntactical doubts.
We have to use set and get methods to such as
Employee()
Employee(empId:int)
Employee(empId:int, payRate:double, weeklyHrs:double)
setId(empId:int):void
setPayRate(payRate:double):void
setHrs(weeklyHrs:double):void
getId():int
getPayRate():double
getHrs():double
getWeeklyPay():double
toString():String
to create an employee class and employee class demo. We have to use two employee id's and type in their weekly hours and pay to return how much they made. Here is what I have down for the Employee class:
//#param
Scanner input = new Scanner(System.in); //Scanner object
public void setID(int empID){
System.out.println("Enter employee 1's id: ");
String input2 = input.next();
int emp1 = Integer.parseInt(input2);
System.out.println("Enter employee 2's id: ");
String input3 = input.next();
int emp2 = Integer.parseInt(input3);
}
//#param
public void setPayRate(double payRate){
System.out.println("Enter employee 1's payrate: ");
String input4 = input.next();
double pay1 = Double.parseDouble(input4);
System.out.println("Enter employee 2's payrate: ");
String input5 = input.next();
double pay2 = Double.parseDouble(input5);
}
//#param
public void setHrs(double weeklyHrs){
System.out.println("Enter employee 1's hours: ");
String input6 = input.next();
double hour1 = Double.parseDouble(input6);
System.out.println("Enter employee 2's hours: ");
String input7 = input.next();
double hour2 = Double.parseDouble(input7);
}
//GET METHODS
public int getID(int empID){
return empID;
}
public double getHrs(double hours){
return hours;
}
public double getWeeklyPay(double pay){
return pay;
}
//DISPLAY ANSWERS
public String toString(int emp1,int emp2,double hour1,double hour2,double pay1,double pay2){
String myString= String.format("The first employee's ID is: " + emp1 +
"The second employee's ID is: " + emp2 +
"The first employee's hours are: " + hour1 +
"The secondemployee's hours are: " + hour2 +
"The first employee's pay: $%,.2f"+ pay1*hour1 +
"The second employee's pay: $%,.2f" + pay2*hour2,
emp1,emp2,hour1,hour2,pay1,pay2);
return myString;
}
}//End of class
I'm just wondering what I would put in my Employee Class Demo so that it would be able to return the toString method?
System.out.println() calls the toString() method automatically on any object you pass into it - alternatively, you can just call it yourself:
Employee e;
// properly initialize e
System.out.println(e); // works
System.out.println(e.toString()); // also works
As a side note, your toString() method is incorrect. It should be a member function of the Employee class - making it a method that takes Employee objects is the wrong way to do it (assuming you want to follow standard Java OOP practices).
The proper method would look something like this:
// Notice no arguments are passed in
public String toString() {
// Instead, we use the "this" variable
return String.format("My ID is %s, my hours are %f, and my pay is $%,.2f", this.empID, this.hours, this.pay);
}
I'm learning object-oriented programming in a Java course, and I'm doing a project where a program creates three types of objects: Address, Date, and Employee. The program stores data of several employees and then displays the data in an array of type Employee.
I'm using four different classes: an Address class, a Date class, and an Employee Class, and an EmployeeTest class that creates the array.
Here is the Address class:
public class Address {
private String Street;
private String City;
private String State;
private int ZipCode;
public Address(String St, String Ci, String Sta, int Zip){
Street = St;
City = Ci;
State = Sta;
ZipCode = Zip;
}
public String getEmployeeAddress(){
return (Street + ", " + City + ", " + State + " " + ZipCode);
}
}
The Date Class:
public class Date {
private int Month;
private int Day;
private int Year;
public Date(int M, int D, int Y){
Month = M;
Day = D;
Year = Y;
}
public String getDateString(){
return (Month + "/" + Day + "/" + Year);
}
}
And, the Employee Class:
public class Employee {
private int EmployeeNum;
public void setEmployeeNum(int ENum){
EmployeeNum = ENum;
}
public int getNum(){
return EmployeeNum;
}
public String getDate(){
return Date.getDateString();
}
public String getName(){
return Name.getEmployeeName();
}
public String getAddress(){
return Address.getEmployeeAddress();
}
}
All of these classes are in the same package (I'm using Eclipse). The point of the Employee class is to create an object of type Employee and be able to get it's Address, Name, and HireDate using the Address, Name, and Date classes.
The place where the array comes into play is here:
import java.util.Scanner;
import java.lang.*;
public class EmployeeTest {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("How many employees will have their data stored today?");
int EmployeeAmount = Integer.parseInt(input.nextLine());
Employee [] EmployeeArray = new Employee[EmployeeAmount];
for (int i = 0; i < EmployeeArray.length; i ++){
System.out.print("What is employee " + (i+1) + "'s employee number?");
int EmployeeNumber = Integer.parseInt(input.nextLine());
EmployeeArray[i] = new Employee();
EmployeeArray[i].setEmployeeNum(EmployeeNumber);
System.out.println("What is the first name of employee " + EmployeeNumber + "?");
String EmployeeFirstName = input.nextLine();
System.out.println("What is the last name of employee " + EmployeeNumber + "?");
String EmployeeLastName = input.nextLine();
Name EmployeeName = new Name(EmployeeFirstName, EmployeeLastName);
System.out.println("Please enter the street address: ");
String StreetAddress = input.nextLine();
System.out.println("Please enter the name of the city: ");
String CityName = input.nextLine();
System.out.println("Please enter the two character code for the state: ");
String StateID = input.nextLine();
System.out.println("Please enter this address's zip code: ");
int ZipCode = Integer.parseInt(input.nextLine());
Address EmployeeAddress = new Address(StreetAddress, CityName, StateID, ZipCode);
System.out.println("Finally, what was the month(#) of the hire date?");
int Month = Integer.parseInt(input.nextLine());
System.out.println("What was the day(#)?");
int Day = Integer.parseInt(input.nextLine());
System.out.println("What was the year?");
int Year = Integer.parseInt(input.nextLine());
Date HireDate = new Date(Month, Day, Year);
}
for (int j = 0; j < EmployeeArray.length; j ++){
System.out.println("Employee number: " + EmployeeArray[j].getNum());
System.out.println("Employee Name: " + EmployeeArray[j].getName());
System.out.println("Employee Address: " + EmployeeArray[j].getAddress());
System.out.println("Employee Hiredate: " + EmployeeArray[j].getDate());
}
}
}
The program prompts the user for the number of employees to be stored in the array, then creates an Employee[] of size EmployeeAmount. The idea of the code is that for each Employee in the Array, all of the variables in the other classes are obtained: Employee Number, Employee Name (first and last), Address (Street Address, City, State Code, Zip Code), Hire Date (Month, Day, Year). After all this is obtained, the second for loop iterates through each Employee and displays the info.
The problem I am having is that in the Employeeclass, Eclipse gives me an error in the getDate(), getName(), and getAddress() methods. When I say for example, return Date.getDateString(), Eclipse says that I cannot make a static reference to a non-static method. It's solution is to make getDateString() static, and I tried this, but the problem is that by making all the methods and variables in the Address, Employee, and Date classes, the values are locked. Meaning that the same data will be displayed for all employees.
Here's what I mean. Below is a sample output if I made all the methods and variables static. The text in between the asterisks is what the user inputs.
How many employees will have their data stored today?**2**
What is employee 1's employee number?**1**
What is the first name of employee 1?
**Bob**
What is the last name of employee 1?
**Jones**
Please enter the street address:
**300 1st Avenue**
Please enter the name of the city:
**New York**
Please enter the two character code for the state:
**NY**
Please enter this address's zip code:
**10001**
Finally, what was the month(#) of the hire date?
**1**
What was the day(#)?
**1**
What was the year?
**2001**
What is employee 2's employee number?**2**
What is the first name of employee 2?
**Bobby**
What is the last name of employee 2?
**Robinson**
Please enter the street address:
**301 1st Avenue**
Please enter the name of the city:
**Los Angeles**
Please enter the two character code for the state:
**CA**
Please enter this address's zip code:
**90001**
Finally, what was the month(#) of the hire date?
**1**
What was the day(#)?
**2**
What was the year?
**2004**
Employee number: 2
Employee Name: Bobby Robinson
Employee Address: 301 1st Avenue, Los Angeles, CA 90001
Employee Hiredate: 1/2/2004
Employee number: 2
Employee Name: Bobby Robinson
Employee Address: 301 1st Avenue, Los Angeles, CA 90001
Employee Hiredate: 1/2/2004
By making all of the variables and methods static, the values are locked as shown, which makes the program useless. Does anyone have a solution to this problem? I need a way to display the information of each employee while referencing the methods in the other classes. Now, normally I would just create all the variables and methods under one class called Employee, but the assignment instructions specify that I need to make individual classes.
You are creating a Name, Address, and Date for each iteration of the for loop. But you have not way, nor do you set them on each Employee instance.
You need to add methods to set the values on each Employee and store the information. Something like this:
public class Employee {
private int employeeNum;
private Name name;
private Date hireDate;
private Address address;
public void setEmployeeNum(int eNum){
employeeNum = eNum;
}
public int getEmployeeNum(){
return employeeNum;
}
public void setHireDate(Date date){
this.hireDate = date;
}
public String getHireDate(){
return hireDate.getDateString();
}
public void setName(Name n){
this.name = n;
}
public String getName(){
return name.getEmployeeName();
}
public void setAddress(Address addy){
this.address = addy;
}
public String getAddress(){
return address.getEmployeeAddress();
}
}
Then in your for loop, set the values:
EmployeeArray[i].setName(EmployeeName);
EmployeeArray[i].setAddress(EmployeeAddress);
EmployeeArray[i].setHireDate(HireDate);
By the way, you should not capitalize variables, only classes.
Variables should be camel-cased.
Fair new to java. Read a few other questions but haven't found the solution yet. Im looking to pass acname, dob and balance1 (all input by the user) to another class. currently it results in nullnullnull. Please help:
First Class:
public static String acname;
public static String dob;
public static String balance1;
public static void main(String[] args) {
switch (menu) {
case 1: Scanner sc=new Scanner(System.in);
System.out.println("Please enter account holders name:");
String acname = sc.nextLine();
Scanner sc2=new Scanner(System.in);
System.out.println("Please enter account holders date of birth:");
String dob = sc2.nextLine();
BankAccount balance1 = new BankAccount(0, 0.10);
balance1.getBalance();
System.out.println("Account Created. Overview and Balance: " + "\n" + acname + "\n" + dob + "\n" + "£" + balance1.getBalance() + "\n");
Second Class:
public class MainMenu {
public static void main(String[] args) {
System.out.println("--WELCOME TO BEAN BANKING LTD--");
System.out.println("");
System.out.println("1. Create new account");
System.out.println("2. View account details and balance");
System.out.println("3. Deactivate account");
System.out.println("4. Exit System");
Scanner scanner = new Scanner(System.in);
int menu = scanner.nextInt();
switch (menu) {
case 1: AccountCreator.main(null);
case 2: System.out.println(AccountCreator.acname + AccountCreator.dob + AccountCreator.balance1);
You are declaring local variables with the same names as your class variables. The local variables will be assumed unless you qualify references to them.
Instead of:
String acname = sc.nextLine();
Just do:
acname = sc.nextLine();
This question already has answers here:
Java: .nextLine() and .nextDouble() differences
(2 answers)
Closed 8 years ago.
I am a beginner of Java. I am trying to create two Scanner objects from a class (which I have created by myself and there i also have created a constructor). I have initialized these two objects by the constructor call and later I want to update these two objects's information by obtaining data from user by Scanner class. When I am creating object by obtaining data from user by using Scanner object, I can create only one object and and the code for the second object are executing thoroughly without obtaining any data from the user. Thus I can create only one object and the code for second object is just displaying in the executing windows without obtaining any data.
Is it that I can't update the data of two objects by Scanner when they are already initialized by constructor call?
Here is the class code from where I want to create two object:
public class Employee {
//instance variables
String firstName;
String lastName;
double salary;
//constructor for three arguments
public Employee(String first_name, String last_name, double month_salary)
{
firstName = first_name;
lastName = last_name;
if(month_salary > 0) //make sure that the salary is not smaller than zero
{
salary = month_salary;
}
}//end of constructor
//set the value of the instance variables
//set first name
public void setFirstName(String first_name)
{
firstName = first_name;
}
//get first name
public String getFirstName()
{
return firstName;
}
//set last name
public void setLastName(String last_name)
{
lastName = last_name;
}
//get last name
public String getLastName()
{
return lastName;
}
//set salary
public void setSalary(double month_salary)
{
if(month_salary > 0) //make sure that the salary is not smaller than zero
{
salary = month_salary;
}
else salary = 0.00;
}
//get salary
public double getSalary()
{
return salary;
}
}
And here are the object's code
import java.util.Scanner;
public class EmployeeTest {
public static void main(String[] args) {
Employee employee1 = new Employee("M", "R", 5000);
Employee employee2 = new Employee("T", "M", 6000);
System.out.println("Display the intial Employee's information\n");
//showing the Employee2's information
System.out.println("Displaying Employee1's information");
System.out.printf("First Name: %s\nLast Name: %s\nSalary: %.2f\n",
employee1.getFirstName(), employee1.getLastName(), employee1.getSalary());
System.out.println();
//showing the Employee2's information
System.out.println("Displaying Employee2's information");
System.out.printf("First Name: %s\nLast Name: %s\nSalary: %.2f\n",
employee2.getFirstName(), employee2.getLastName(), employee2.getSalary());
System.out.println();
//create an scanner object to get information from user
Scanner input = new Scanner(System.in);
//obtain employee's first name from user
System.out.print("Please enter the first name of employee1: ");
String fName1 = input.nextLine();
//set the first of employee1
employee1.setFirstName(fName1);
//obtain employee's last name from user
System.out.print("Please enter the last name of employee1: ");
String lName1 = input.nextLine();
//set the last of employee1
employee1.setLastName(lName1);
//set the salary employee1's
System.out.print("Please enter employee's salary: ");
double empl_salary1 = input.nextDouble();
//obtain the employe1's salary
employee1.setSalary(empl_salary1);
//display the updated employee1's information
System.out.println("Updated information of employee's information");
System.out.printf("First name :%s\nLast name: %s\nSalary: %.2f\n",
employee1.getFirstName(),employee1.getLastName(), employee1.getSalary());
//obtain employee2's first name from user
System.out.print("Please enter employee2'first name: ");
String fName2 = input.nextLine();
//set the first name of employee2
employee2.setFirstName(fName2);
//obtain employee's last name from user
System.out.print("Please enter the employee2's last name: ");
String lName2 = input.nextLine();
//set the last name of employee2
employee2.setLastName(lName2);
//obtain the salary employee2's
System.out.print("Please enter employee2's salary: ");
double empl_salary2 = input.nextDouble();
//set the employe1's salary
employee2.setSalary(empl_salary2);
}
}
I don't know where is the problem?
Thanks for your time and assistance!
Add input.nextLine(); just before obtaining data for second employee:
input.nextLine();
//obtain employee2's first name from user
System.out.print("Please enter employee2'first name: ");
String fName2 = input.nextLine();
It is because input.nextDouble(); "consumes" only double value, leaving the newline character you entered "unconsumed".