Print statements with objects. Java - java

I am currently writing a program that models an employee as a way to get started in object oriented programming. It gets a name, hire date, and address of each employee, and then must display the information
My current program has no compile errors, but I am confused as to how I would go about printing the information in a neat manner. Thanks!
public class Unit10Assignment1
{
public static void main( String [] args )
{
int numEmployees = Input.getInt("How many employees are you storing?");
Employee database[] = new Employee[numEmployees];
for( int i = 0; i < numEmployees; i++ )
{
String firstName = Input.getString("What is an employee's first name?");
String lastName = Input.getString("What is their last name?");
String street = Input.getString("What street do they live on?");
String city = Input.getString("What city do they live in?");
String state = Input.getString("What state do they live in?(2 characters)");
String zip = Input.getString("What is their zipcode?");
int month = Input.getInt ("In what month was he/she hired?(number)");
int day = Input.getInt ("On what day was he/she hired(number)");
int year = Input.getInt ("In what year was he/she hired?(number)");
database[i] = new Employee(firstName, lastName, street, city, state, zip, month, day, year);
}
}
}
class Employee
{
Name Name;
Address Address;
Date Date;
Employee( String firstName, String lastName, String street, String city, String state, String zip, int month, int day, int year)
{
Name = new Name( firstName, lastName );
Address = new Address( street, city, state, zip );
Date = new Date( month, day, year );
}
}
class Name
{
String firstName = " ";
String lastName = " ";
public Name(String newFirstName, String newLastName)
{
firstName = newFirstName;
lastName = newLastName;
}
public String getFirst()
{
return firstName;
}
public String getLast()
{
return lastName;
}
}
class Address
{
String street = " ";
String city = " ";
String state = " ";
String zip = " ";
public Address(String newStreet, String newCity, String newState, String newZip)
{
street = newStreet;
city = newCity;
state = newState;
zip = newZip;
}
public String getStreet()
{
return street;
}
public String getCity()
{
return city;
}
public String getState()
{
return state;
}
public String getZip()
{
return zip;
}
}
class Date
{
int month = 0;
int day = 0;
int year = 0;
public Date(int newMonth, int newDay, int newYear)
{
month = newMonth;
day = newDay;
year = newYear;
}
public int getMonth()
{
return month;
}
public int getDay()
{
return day;
}
public int getYear()
{
return year;
}
}
Having trouble formatting, hopefully you can understand it. If there are any problems with my current code, pointing them out to me would be appreciated. Also, my instructor uses his own class to get user input so no need to worry about that.

For pretty printing an objects contents, I prefer overriding the toString method.

You could override the toString-method in Name, Address and Date, and let Employee use these methods in its own toString.
E.g:
Name
#Override
public String toString() {
return firstName + " " + lastName;
}
Address
#Override
public String toString() {
return street + ", " + city + ", " + state + ", " + zip;
}
Date
#Override
public String toString() {
return String.valueOf(month) + "." +
String.valueOf(day) + "." +
String.valueOf(year);
}
Employee
#Override
public String toString() {
return name.toString() + "\n" +
date.toString() + "\n" +
address.toString();
}

by the way, you can use astyle to format your code

Related

Classes and subclass printing

I am trying to print the grade for the student subclass, i feel like i need some type of if statement or array.I am trying to make a code that can be passed a number such as 3 for "Junior" but can also be called through a code such Student.JUNIOR to print the grade level junior. my desired output is:
class Person {
String name;
String campus;
String phone;
String email;
int FRESHMAN = 1;
int SOPHMORE = 2;
int JUNIOR = 3;
int SENIOR = 4;
public Person(String n, String cam, String cell, String mail) {
name = n;
campus = cam;
phone = cell;
email = mail;
}
public String toString() {
return "Name:" + name + "; Campus:" + campus + "; Phone:" + phone + "; Email:" + email + " ";
}
}
class Student extends Person {
int grade;
public Student(String n, String cam, String cell, String mail, int grade) {
super(n, cam, cell, mail);
}
public String toString() {
return super.toString() + "\nClass:";
}
}
class Employee extends Person {
private String title;
public Employee(String n, String cam, String cell, String mail, String position) {
super(n, cam, cell, mail);
title = position;
}
public String toString() {
return super.toString() + "\nTitle:" + title;
}
}
public class Exam3c {
public static void main(String[] args) {
String name = "David";
String campus = "Terry";
String phone = "302-573-3254";
String email = "Genos#edu";
Person P1 = new Person(name, campus, phone, email);
System.out.println("P1: \n" + P1);
Student S1 = new Student(name, campus, phone, email, 1);
System.out.println("S1: \n" + S1);
Student S2 = new Student("Bill While", "Nowhere", "012-345-6789", "bw#nowhere.edu", 3);
System.out.println("S2: \n" + S2);
Employee E1 = new Employee(name, campus, phone, email, "Faculty");
System.out.println("E1: \n" + E1);
}
}
I think you're looking for enums. They have a lot of very useful features; in addition to being nicely type safe in a way that "Magic Ints" are not, you can also fairly fluidly treat them as Strings for debugging.

How to call on a field from a new object

I created a class called "Person" here it is: (ignore the toString. I haven't done anything with that yet)
public class Person {
public String firstName;
public String middleName;
public String lastName;
public Person() {
firstName = "first";
middleName = "middle";
lastName = "last";
}
public Person(String first, String middle, String last) {
firstName = first;
middleName = middle;
lastName = last;
}
public String toString() {
return (firstName + " " + middleName + " " + lastName);
}
public String getFirstName() {
return firstName;
}
public String getMiddleName() {
return middleName;
}
public String getLastName() {
return lastName;
}
}
And then I created an implementation class in a new file, this is it:
import java.util.*;
public class TestProgPerson
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
String first;
String middle;
String last;
Person name = new Person("Joe", "Smith", "Blow");
System.out.println("Name: " + name);
System.out.println("Please enter a last name, to check if it corresponds with the persons last name: " );
last = console.nextLine();
if (last == (objectReference.lastName))
System.out.println("The last name you entered matches the persons last name");
else
System.out.println("The last name you entered does not match the persons last name");
}
}
So what I want it to do is this: Have an object with the first name, middle name, and last name. Output that name. (The program works this far). Then I want to have the user enter a last name, and the program checks to see if the entered last name is the same as the last name in the object. How do I go about calling just an individual string from that object?
Here you are calling the name object of the class but not any field of that class.
System.out.println("Name: " + name);
You can call fields here by using the object of the class and the dot operator.
For Example.
System.out.println("Name: " + name.firstName + " " + name.middleName + " " + name.lastName);
Moreover because strings are Objects and should be compared with the equals method.

Null objects in arrays of objects java

I am getting the error Exception in thread “main” java.lang.NullPointerException?. on my program. What I did was create an array of objects (the array is dbase[], the object is employee). the employee object creates more objects (date, name, and address) that have setter and getter methods. I am getting this error when tryinig to access these object's getter methods when trying to use something such as dbase[0].date.getMonth. I believe this is something wrong with creating the array. I have not included the date or address classes in the interest of saving space, because are basically the same as the name class. thanks for the help.
edit: The error occurred at the second line of the printing block in the main method in the for loop. It occurs at dbase[j].name.getFirst() at line 28
public class test {
public static void main (String[] args) {
int i = Input.getInt ("How many employees would you like to enter? ");
int j;
Employee [] dbase = new Employee [i];
for (j = 0; j < i; j++) {
dbase[j] = new Employee();
}
for (j = 0; j < i; j++) {
String firstName = Input.getString ("What is an employee " + (j + 1) + "'s first name?");
String lastName = Input.getString ("What is this employee's last name?");
String street = Input.getString ("On what street does this employee live?");
String city = Input.getString ("In which city does this employee live?");
String state = Input.getString ("In which state does this employee live? (abbreviation)");
String zipcode = Input.getString ("What is this employee's zip code?");
int month = Input.getInt ("In what month was this employee born? (numeric - January = 1 )");
int day = Input.getInt ("On what day was this employee born?");
int year = Input.getInt ("In what year was this employee born?");
int employeeID = Input.getInt ("What should this employee's employee id be?");
dbase[j] = new Employee(firstName, lastName, street, city, state, zipcode, month, day, year, employeeID);
}
for (j = 0; j < i; j++) {
System.out.print ( "Employee number " + (j + 1) + " is named ");
System.out.print ( dbase[j].name.getFirst() + " " + dbase[j].name.getLast() + " and lives on " + dbase[j].address.getStreet());
System.out.print ( " in " + dbase[j].address.getCity() + " " + dbase[j].address.getState() + ", " + dbase[j].address.getZipcode());
System.out.print ( ". He will be hired on " + dbase[j].date.getMonth() + "-" + dbase[j].date.getDay() + "-" + dbase[j].date.getYear() );
System.out.print ( " and his ID is " + dbase[j].getEmployeeID());
System.out.println ();
}
}
}
class Employee {
int employeeID = 0;
name name;
address address;
date date;
Employee(){
}
Employee( String firstName1, String lastName1, String street1, String city1, String state1, String zipcode1, int month1, int day1, int year1, int employeeID1 ) {
name name = new name( firstName1, lastName1 );
address address = new address( street1, city1, state1, zipcode1 );
date date = new date( month1, day1, year1);
employeeID = employeeID1;
}
int getEmployeeID() {
return employeeID;
}
}
class name {
String firstName = " ";
String lastName = " ";
name(String newFirstName, String newLastName) {
firstName = newFirstName;
lastName = newLastName;
}
String getFirst() {
return firstName;
}
String getLast() {
return lastName;
}
}
In your constructor for Employee, you're assigning to local variables, not to the fields of the same name.
Employee( String firstName1, String lastName1, String street1, String city1, String state1, String zipcode1, int month1, int day1, int year1, int employeeID1 ) {
name name = new name( firstName1, lastName1 );
address address = new address( street1, city1, state1, zipcode1 );
date date = new date( month1, day1, year1);
employeeID = employeeID1;
}
You can eliminate this problem by removing the type names from the assignment statements:
Employee( String firstName1, String lastName1, String street1, String city1, String state1, String zipcode1, int month1, int day1, int year1, int employeeID1 ) {
name = new name( firstName1, lastName1 );
address = new address( street1, city1, state1, zipcode1 );
date = new date( month1, day1, year1);
employeeID = employeeID1;
}
In addition, you should consider beginning all your type names with an uppercase character. This is almost universal Java style, and helps you identify them at a glance.
class Name { ... }
class Date { ... }
class Address { ... }
One way to reduce the likelihood of name collisions between member and local variables is to adopt a different naming scheme for the former. This is not generally accepted Java style, and some feel antipathy toward it as an incursion of a style that originated in C++. However, it can reduce risk.
class Employee {
int m_employeeID = 0;
Name m_name;
Address m_address;
Date m_date;
...
}
When you have a variable holding an object in Java, this variable is a reference to the object. That means that multiple variables can point to the same object and also that they might point to no object at all. That's null.
When you access something that belongs to an object, either a method or a field, you are dereferencing. However if the variable points to no object (that's null) you get a nullpointer exception.
In your case that could be dbase[j].name or one of the others in the last for-body. And there are two dereferenciations going on: first dbase[j] (I don't see a problem there; actually you are creating multiple objects, i.e. your first for-loop is not needed), or the value of name within your object is not set. Either because Input.getString returned null (we cannot say what that is, because that info is missing from your post) or you didn't set the value in the Employer constructor, which is the case here.
Within the constructor you create local variables.
name name = new name( firstName1, lastName1 );
Instead of
this.name = new name( firstName1, lastName1 );
As a general tip you should look into debuggers (like the one in eclipse or netbeans or whichever ide you use). They can really help you with this kind of problems.

odd output when using multiple classes

I am very new with java programming and I am close to finishing a very big project for me. I am trying to make an employee registry that simply relays information back. Whenever I enter the info it just returns stuff like Name#5a965654. My classes are below and any help would be appreciated.
Main:
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner Input = new Scanner(System.in);
System.out.println("Enter the number of employees to enter.");
int employeeCount = Input.nextInt();
Input.nextLine();
Employee employees[] = new Employee[employeeCount];
String firstName;
String lastName;
String street;
String city;
String state;
String zipCode;
String monthHired;
String dateHired;
String yearHired;
int employeeID;
for(int x = 0; x < employeeCount; x++)
{
System.out.println("Please enter the first name of employee " + (x + 1));
firstName = Input.nextLine();
System.out.println("Please enter the last name of employee " + (x + 1));
lastName = Input.nextLine();
System.out.println("Please enter the street of employee " + (x + 1));
street = Input.nextLine();
System.out.println("Please enter the city of employee " + (x + 1));
city = Input.nextLine();
System.out.println("Please enter the state of employee " + (x + 1));
state = Input.nextLine();
System.out.println("Please enter the zip code of employee " + (x + 1));
zipCode = Input.nextLine();
System.out.println("Please enter the month hired for employee " + (x + 1));
monthHired = Input.nextLine();
System.out.println("Please enter the date hired for employee " + (x + 1));
dateHired = Input.nextLine();
System.out.println("Please enter the year hired for employee " + (x + 1));
yearHired = Input.nextLine();
Name name = new Name(firstName, lastName);
name.setName(firstName, lastName);
Address address = new Address(street, city, state, zipCode);
DateOfHire hireDate = new DateOfHire(monthHired, dateHired, yearHired);
employees[x] = new Employee(name, address, hireDate, x);
}
for(int x = 0; x < employeeCount; x++)
{
employees[x].printInfo(x);
}
}
}
Employee class:
public class Employee
{
private Name name;
private Address address;
private DateOfHire hireDate;
int ID;
public Employee()
{
}
public Employee(Name name, Address address, DateOfHire hireDate, int x)
{
this.name = name;
this.address = address;
this.hireDate = hireDate;
this.ID = x;
}
public void printInfo(int x)
{
System.out.println("Employee-" + (x + 1));
System.out.println("Name: " + this.name);
System.out.println("Address: " + this.address);
System.out.println("Date of Hire: " + this.hireDate);
}
}
Format of Name, DateHired, and Address classes:
public class Name
{
private String firstName;
private String lastName;
public Name()
{
}
public Name(String firstName, String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public void setName(String firstName, String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public String getName()
{
return firstName + " " + lastName;
}
}
A Name is not the same as a String, so when you print this.name in Employee.printInfo, it prints Name#[numbers], indicating that what you're printing is a Name object at the location described by the numbers.
Try replacing that line with
System.out.println("Name: " + this.name.getName());
Also, you'll need to do something similar for the Address and DateOfHire, but I don't know what you have implemented for those, so I can't really say what specifically to do. Essentially, though, you'll need a method that gives a string representation of whatever object it is that you want to print.
All classes in Java extend from the java.lang.Object which has a method toString(). This method is implemented as
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
Whenever you call
System.out.println("Name: " + this.name);
String concatenation is done by implicitly calling the toString() method of your instance. If your class doesn't implement (override) the toString() method, then Object's implementation is used.
See the String Conversion rules in the Java Language Specification.
Otherwise, the conversion is performed as if by an invocation of the
toString method of the referenced object with no arguments; but if the
result of invoking the toString method is null, then the string "null"
is used instead.
Since your Name class does not have a toString() method, then its parent class' method is called, ie. Object#toString() and you get the output you see.
You should override the toString() method in all your classes. For example,
public class Name
{
private String firstName;
private String lastName;
public Name()
{
}
public Name(String firstName, String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public void setName(String firstName, String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public String toString()
{
return firstName + " " + lastName;
}
public String getName()
{
return firstName + " " + lastName;
}
}
It does not matter than toString() and getName() return the same thing in this case. You have to follow the language spec.
You should implement String toString() method if you wanna print an object

I need help, my java program is returning nothing when i compile it

I'm a college student doing a Java homework. I've created this program that allows user to enter a job information.
The problem is that my program doesn't return information entered.
I look at my program for a while, but I know it's something simple I'm missing.
public class Employee
{
String name; // Employee name
String employeeNumber; // Employee number
String hireDate; // Employee hire date
int shift; // Employee shift
double payRate;
public void setEmployeeNumber(String e)
{
if (isValidEmpNum(e))
{
employeeNumber = e;
}
else
{
employeeNumber = "";
}
}
public Employee(String name, String e, String hireDate, double payRate, int shift)
{
this.name = name;
this.setEmployeeNumber(e);
this.hireDate = hireDate;
this.payRate = payRate;
this.shift = shift;
}
public Employee()
{
name = "";
employeeNumber = "";
hireDate = "";
}
public void setpayRate(double payRate)
{
this.payRate = payRate;
}
public double getpayRate()
{
return payRate;
}
public void setshift(int shift)
{
this.shift = shift;
}
public int getshift()
{
return shift;
}
public void setName(String name)
{
this.name = name;
}
public void setHireDate(String hireDate)
{
this.hireDate = hireDate;
}
public String getName()
{
return name;
}
public String getEmployeeNumber()
{
return employeeNumber;
}
public String getHireDate()
{
return hireDate;
}
private boolean isValidEmpNum(String e)
{
boolean status = true;
if (e.length() != 5)
status = false;
else
{
if ((!Character.isDigit(e.charAt(0))) ||
(!Character.isDigit(e.charAt(1))) ||
(!Character.isDigit(e.charAt(2))) ||
(e.charAt(3) != '-') ||
(!Character.isLetter(e.charAt(4))) ||
(!(e.charAt(4)>= 'A' && e.charAt(4)<= 'M')))
{
status = false;
}
}
return status;
}
public String toString()
{
String str = "Name: " + name + "\nEmployee Number: ";
if (employeeNumber == "")
{
str += "INVALID EMPLOYEE NUMBER";
}
else
{
str += employeeNumber;
}
str += ("\nHire Date: " + hireDate);
return str;
}
}
I declared this in another class.
import javax.swing.JOptionPane;
public class ProductionWorkerDemo extends Employee
{
public static void main(String[] args)
{
String name; // Employee name
String employeeNumber; // Employee number
String hireDate; // Employee hire date
int shift; // Employee shift
double payRate; // Employee pay
String str;
String str2;
name = JOptionPane.showInputDialog("Enter your name: ");
employeeNumber = JOptionPane.showInputDialog("Enter your employee number: ");
hireDate = JOptionPane.showInputDialog("Enter your hire date: ");
str = JOptionPane.showInputDialog("Enter your shift: ");
payRate = Double.parseDouble(str);
str2 = JOptionPane.showInputDialog("Enter your payrate: ");
payRate = Double.parseDouble(str2);
ProductionWorkerDemo pw = new ProductionWorkerDemo();
System.out.println();
System.out.println("Name: " + pw.getName());
System.out.println("Employee Number: " + pw.getEmployeeNumber());
System.out.println("Hire Date: " + pw.getHireDate());
System.out.println("Pay Rate: " + pw.getpayRate());
System.out.println("Shift: " + pw.getshift());
}
}
You need to use an appropiate constructor or the set* methods to set the fields on the object. Currently, all of them are empty, thus the get* methods return either nothing or default values.
Also, you shouldn't extend Employee with the class containing the main method, just use the Employee class directly (the idea behind inherting from a class is to extend it, in your case you just need it as an object so save data, so don't derive from it but use it):
import javax.swing.JOptionPane;
public class ProductionWorkerDemo
{
public static void main(String[] args)
{
String name; // Employee name
String employeeNumber; // Employee number
String hireDate; // Employee hire date
int shift; // Employee shift
double payRate; // Employee pay
String str;
String str2;
name = JOptionPane.showInputDialog("Enter your name: ");
employeeNumber = JOptionPane.showInputDialog("Enter your employee number: ");
hireDate = JOptionPane.showInputDialog("Enter your hire date: ");
str = JOptionPane.showInputDialog("Enter your shift: ");
payRate = Double.parseDouble(str);
str2 = JOptionPane.showInputDialog("Enter your payrate: ");
payRate = Double.parseDouble(str2);
Employee pw = new Employee(/*provide arguments here*/);
System.out.println();
System.out.println("Name: " + pw.getName());
System.out.println("Employee Number: " + pw.getEmployeeNumber());
System.out.println("Hire Date: " + pw.getHireDate());
System.out.println("Pay Rate: " + pw.getpayRate());
System.out.println("Shift: " + pw.getshift());
}
}
You are setting the employee information on local variables only. You are not passing them to the ProductionWorkerDemo nor it's super class Employee.
You don't need to extend the Employee with the ProductionWorkerDemo as the ProductionWorkerDemo is not an Employee. You can just remove the extends Employee text.
You're not passing the variables to the Employee. You've created a constructor in the Employee class that takes them all so you can use it
Employee pw = new Employee(name, employeeNumber, hireRate, payRate, shift);
Now you'll notice that you haven't asked for the shift.
First you need to add the constructor you the Demo Class:
public class ProductionWorkerDemo extends Employee{
public ProductionWorkerDemo(String name, String e, String hireDate, double payRate, nt shift){
{
super(name, e, hireDate, payRate, shift);
}
}
Then in your class you need to instantiate:
ProductionWorkerDemo pw = new ProductionWorkerDemo(name,
employeeNumber,
hireDate,
payRate,
shift);
You are declaring variables called name, employeenumber, etc in your main method. When you try to use them, it's going to use those, not your class variables.
why don't you try making a new ProductionWorkerDemo based on the constructor you defined in Employee class?
ProductionWorkerDemo pw = new ProductionWorkerDemo(name,employeeNumber,hireDate,payRate,shift);
And also, your payRate is being assigned twice, you should change the first one to shift, and use Integer.parseInt
You have local variables in main() whose values you are setting. You then create a ProductionWorkerDemo object, who has instance variables with the same names, but are all initially empty, due to the constructor setting them that way.
You never pass your local variables in to your ProductionWorkerDemo object, so when you call the getters they return the empty values.
I fix the problem with my program, thanks for the help everyone.
I was not passing the variables to the Employee.
I add this statement to ProductionWorkerDemo class.
Employee pw = new Employee(name, employeeNumber, hireRate, payRate, shift);
P.S. You can close this thread.

Categories