Java toString Method - Not printing correctly - java

I'm trying to get the toString from the class Employee, but all it does is give me an output of [ ]. I got the input for the toString method, but any ideas on how to get it to carry out to the output?
public class A5
{ // begin class
public static void main(String[] args)
{ // begin main
// ********** CREATE OBJECTS **********
ArrayList<Employee> employeeInfo = new ArrayList<Employee>();
// ********** GET INPUT **********
// get the employee's ID
System.out.println("\nEnter your employee ID.");
ID = keyboard.nextInt(); //get the input and set it to the local varaible ID
//System.out.println("Employee ID: " + ID);
// get the employee's hours worked
System.out.println("\nEnter the amount of hours you worked this week.");
Hours = keyboard.nextInt(); //get the input and set it to the local varaible HoursWorked
//System.out.println("Hours worked: " + Hours);
// get the employee's wage
System.out.println("\nEnter your wage.");
Wage = keyboard.nextDouble(); //get the input and set it to the local varaible Wage
//System.out.println("Employee wage: " + Wage);
// ********** OUTPUT **********
System.out.println(employeeInfo.toString());
// ********** CLOSING MESSAGE **********
System.out.println("\nEnd of Processing!");
} // end main
} // end class
And the other class is:
public class Employee
{ // begin class
private int ID; // employee's id
private int Hours; // number of hours worked
private double Wage; // pay per hour
public Employee(int IDnumber)
{
ID = IDnumber;
}
public int getID()
{
return ID;
}
public void setWage(double HourlyWage)
{
Wage = HourlyWage;
}
public double getWage()
{
return Wage;
}
public void setHours(int hoursWorked)
{
Hours = hoursWorked;
}
public double getHours()
{
return Hours;
}
public String toString() // overrides the toString method inherited from object
{ // begin toString
String strout = "\nId \t\t Hours \t\t Rate \t\t Regular Pay \t Overtime Pay \t Gross Pay\n";
strout += ID + "\t " + Hours + "\t\t\t $" + (df1.format(Wage)));
return strout;
} // end toString
} // end class

You are calling the toString method of the ArrayList, not of any Employee. In fact you did not yet create an instance of that class. Try:
System.out.println(new Employee());

EDIT:
First:
OK, well, you need atleast to make some Employee objects and add them to your list ;) Otherwise, there is "nothing" (which prints out to "nothing"). So after you read all your stuff from the user's input (ID and so) make a new Employee out of it:
// make a new employee
Employee employee = new Employee(id); // pass your id
employee.setWage(...); // pass your wage
... // pass other things
// add it to the list of course
employeeInfo.add(employee);
Now there is an employee in the list which you can print. You can test if something is on the list by asking for its size:
System.out.println(employeeInfo.size());
Second:
You don't call toString() on your employee class, which you properly want to print. You call it on your list of employees. Therefor you will see the result of the toString() method of the ArrayList class (which is not what you expect, but what is correct). Instead, iterate over the list and print every employee. Note that the toString() method will be called automatically, since System.out.println will convert your object to a string (which actually means to call this method).
Try this:
for(Employee employee: employeeInfo)
System.out.println(employee);

Your employeeInfo object seems to be empty, and thus you are printing an empty list.
Make sure you put values in it before printing.
Note that the toString() of the ArrayList is implemented to recursively invoke toString() of its object, so it is fine to use ArrayList.toString() to print the entire ArrayList - if that's what you want. No need to iterate for all elements.

You are printing the toString of an Array. employeeInfo is an ArrayList of Employees.
Iterate and print employees like:
for (Employee e : employeeInfo)
{
System.out.println(e.toString());
}

Related

How to put a object in a linked list?

I'm trying to make a bank record and trying to use linked list. I made my bank class and I'm trying to put that as an object in my main class and print the output. So If I enter James as a first name, black as my last name and 200 as balance. It should print the output: FirstName: James, Lastname: Black, Balance: 200. If I add another first,last, balance. It should print the new record with the old record.
Example:
First name Lastname Balance
James Shown 4000
Kyle Waffle 2000
Bank Class:
public class Customer2 {
String Firstname,Lastname;
public int balance, amount;
int total=0;
int total2=0;
Scanner input = new Scanner(System.in);
public Customer2(String n, String l, int b){
Firstname=n;
Lastname=l;
balance=b;
}
public void withdraw(int amount){
total=balance-amount;
balance=total;
}
public void deposit(int amount){
total=balance+amount;
balance=total;
}
public void display(){
System.out.println("FirstName: "+" Lastname: "+" Balance");
System.out.println(Firstname+" "+Lastname+" " +balance);
}
Main class:
LinkedList<Customer2> list = new LinkedList<Customer2>();
list.add("Bob");
list.getfirst("Lastname");
You should create a new customer2 Object and then add that to your linked list
It would look like this:
Main Class:
Customer2 customer = new Customer2("Bob", "Doe", 1000);
list.add(customer);
Bob would now be added to the linked list.
If you wanted to retrieve bob from the linked list you could iterate through the list until you found bob and then call display on that object.
Or you could use getFirst (if bob is the first in the list)
that would look like this:
list.getFirst().display();
There are other methods in the linked list class that you can use to add or get if you know the position. Here is a link: http://www.tutorialspoint.com/java/java_linkedlist_class.htm
also I think this is what you wanted your display() method to be:
public void display(){
System.out.println("First Name: " + firstName + ", Last Name: " + lastName + ", Balance: " + balance);
you should also use lower case letters to start variable names as it is good naming convention aka. Firstname becomes firstname.
If you want to put element in LinkedList<Customer2> list you need use method list.add(customer) where customer is object from class Customer2.
LinkedList<Customer2> list = new LinkedList<Customer2>();
Customer2 c = new Customer2("firstName","lastName",1000);
list.add(c);
System.out.println(list);
Override toString() in Customer2 Class:
#Override
public String toString(){
return "FirstName: "+fristName+",lastName: "+lastName,+"balance" +balance;
}
//toString()
//returns string for the object
to print all the objects in list, each Customer2 object in a new line
for(Customer2 c : list){
System.out.println(c);
}

Creating Methods and Classes (Java)

I am trying to write a class called Student that is supposed to work with a StudentDriver. However, I am having a very hard time wrapping my head around the concept of methods and classes. I do not know how to receive and return data. Moreover, I don't even know if I am declaring my data correctly. Please help me. I would greatly appreciate it.
Also when I compiled the Student it says that it cannot find the symbol this.setGPA. How so? When in the driver it has .setGPA.
Thank you.
// This will be the "driver" class for the Student class created in
// MinilabWritingClasses (It looks very complicated because of all
// the comments, but it really just creates instances of Student and
// tells them to do things...)
public class StudentDriver
{
public static void main(String[ ] args)
{
//create an instance of Student
System.out.println("***** Creating a Student, calling the default constructor");
Student stud1 = new Student();
//print it so we can see what the default values were for the class data
//note that its toString() will be called automatically
System.out.println("\n***** printing it - notice the default values (set by Java)");
System.out.println(stud1);
//create another instance of a Student, passing in initial values to its constructor
System.out.println("\n***** Creating another Student, passing initial values to its constructor");
Student msBoss = new Student("Bill Gates", 56, 'm', 3.2, true);
//tell it to return its age
System.out.println("\n***** telling it to return its age.");
int theAge = msBoss.getAge();
System.out.println("Its age is: " + theAge);
//print it - note that its toString() will be called automatically;
System.out.println("\n***** printing it - see if values are correct");
System.out.println(msBoss);
//ask it if it is on probation
System.out.println("\n***** asking it if it is on probation (check answer)");
System.out.println("onProbation() returned: " + msBoss.onProbation());
//tell it to change its gpa to 1.3
System.out.println("\n***** telling it to change its gpa to 1.3");
msBoss.setGPA(1.3);
//print it now
System.out.println("\n***** printing it - see if the values are correct");
System.out.println(msBoss);
//ask it if it is on probation now
System.out.println("\n***** asking it if it is on probation (check answer)");
boolean boolAnswer = msBoss.onProbation();
System.out.println("onProbation() returned: " + boolAnswer);
//tell it to complain
System.out.println("\n***** telling it to complain");
System.out.println("complain() returned: " + msBoss.complain());
//tell it to change its onScholarship field to false
System.out.println("\n***** telling it to change its onScholarship field to false");
msBoss.setOnScholarship(false);
//print it now
System.out.println("\n***** printing it - see if the values are correct");
System.out.println(msBoss);
//ask it if it is on probation now
System.out.println("\n***** asking it if it is on probation (check answer)");
boolAnswer = msBoss.onProbation();
System.out.println("onProbation() returned: " + boolAnswer);
//create a different student, tell it to have some different values, and tell it to print itself
System.out.println("\n***** creating a different Student, passing initial values to its constructor");
Student stud2;
stud2 = new Student("Hillary Clinton", 64, 'f', 2.0, true); //notice-can define variable and create it in 2 steps
//print it
System.out.println("\n***** printing it - see if the values are correct");
System.out.println(stud2);
//ask it if it is on probation now
System.out.println("\n***** asking it if it is on probation (check answer)");
boolAnswer = stud2.onProbation();
System.out.println("onProbation() returned: " + boolAnswer);
}
}
Here is the class that I am writing.
public class Student
{
private String name;
private int age;
private char gender;
private double gpa;
private boolean onScholarship;
public Student()
{
}
public Student(String newName, int newAge, char newGender, double newGPA, boolean newScholarship)
{
this.name = newName;
this.age = newAge;
this.gender = newGender;
this.gpa = newGPA;
this.onScholarship = newScholarship;
}
public int getAge(int newAge)
{
return age;
}
public double setGPA (double newGPA)
{
this.setGPA = newGPA;
}
public boolean setOnScholarship (boolean newScholarship)
{
this.setOnScholarship = newScholarship;
}
public String toString()
{
return this.name + "\t" + this.age + "\t" + this.gender + "\t" + this.setGPA + "\t" + this.setOnScholarship;
}
public boolean onProbation()
{
if (onScholarship==true && gpa < 2.0)
return true;
else
return false;
}
}
Try to change this line:
this.setGPA = newGPA;
to this:
this.gpa = newGPA;
setGPA symbol not found is because there is no setGPA field (it is a method). You are trying to change the gpa field.
You also don't need the empty public Student() {} constructor -- this is automatically created by Java.
Also, as #Sam pointed out, since setOnScholarship() doesn't return anything, you can change the return type boolean to void. This is because there is no return statement, and this returning of nothing is a void type.
Overall, though, you have a good understanding on creating instances of another class (i.e., creating Students).
On request (although it doesn't have much to do with your code), here is a brief summary on static.
The static keyword is used with methods and fields that are not used with an instance of that class, but the class itself.
For example, in your case, pretty much all of the Student fields and methods are non-static, because they are properties of Student objects:
this.gpa;
this.setGpa();
On the other hand, if it were not changing a variable related to a single object, for example the total number of students, you could create a static field in Student:
public class Student {
// non-static fields for each instance
public double gpa;
// static field for the class
public static numStudents;
public Student() {
// create student by setting object (non-static) fields, for example...
this.gpa = 3.2;
// edit static variable
numStudents++; // notice how there is no `this` keyword - this changes a static variable
}
}
... and from StudentDriver, numStudents can be retreived with:
Student.numStudents; // notice how this is like `this.[property]`, but with the class name (Student) - it is an instance of the class
I hope this helps! OOP programming is a difficult topic that can't be explained so simply.

How to display contents of an object in Java

Ok, now I think I've given up all hope of finding solution to what should to be a simple problem. Basically, I'm creating a students' record system that stores students' details in an ArrayList. I first created a constructor in the Student class to specify what entries each student will have. I then created an instance of the Student class in the main class (i.e. class with the main method) and then added the student object to the studentList ArrayList.
By the way, instead of hard-coding the student details, my initial aim was to let the user enter the details and then I'll use a Scanner or BufferedReader object to get the details stored in the Student object, and then to the ArrayList but I'm having trouble with that as well; so I'll probably tackle that problem as soon as I'm done with this one.
Anyway, I'm expecting the output to print out the students' details but instead I get a memory location (i.e. [studentrecordsys.Student#15c7850]). I'm aware that I need to override the toString method but how exactly this is done is what I can't seem to get. I get syntax errors everywhere as soon as I enter the #Override code block for the toString method. Here's what I've tried:
import java.util.*;
class Student {
private String studentID;
private String studentName;
private String studentAddress;
private String studentMajor;
private int studentAge;
private double studentGPA;
Student (String studentID, String studentName, String studentAddress, String
studentMajor, int studentAge, double studentGPA){
this.studentID=studentID;
this.studentName=studentName;
this.studentAddress=studentAddress;
this.studentMajor=studentMajor;
this.studentAge=studentAge;
this.studentGPA=studentGPA;
}
}
public static void main(String[] args) {
Student ali = new Student("A0123", "Ali", "13 Bond Street", "BSc Software Engineering", 22, 3.79);
List<Student> studentList = new ArrayList<>();
studentList.add(ali);
#Override
String toString() {
StringBuilder builder = new StringBuilder();
builder.append(ali).append(studentList);
return builder.toString();
}
System.out.println(builder);
}
You need to implement the toString() on the Student object.
public class Student {
...
Your existing code
...
#Override
public String toString() {
return studentID + ", " + studentName + ", " + //The remaining fields
}
}
then in your main method, call
for (Student student : studentList) {
System.out.println(student.toString());
}
You to override toString method because it is going to give you clear information about the object in readable format that you can understand.
The merit about overriding toString:
Help the programmer for logging and debugging of Java program
Since toString is defined in java.lang.Object and does not give valuable information, so it is
good practice to override it for subclasses.
Source and Read more about overriding toString
public String toString() {
return "Studnet ID: " + this.studentID + ", Student Name:"
+ this.studentName+ ", Studnet Address: " + this.studentAddress
+ "Major" + this.studentMajor + "Age" + this.studentAge
+ GPA" + this.studentGPA ;
}
You get errors because you have to Override the toString method inside the class you want to use it for. i.e you have to put the method, with the #Override inside your Student class.
And you can call it like this:
System.out.println(studentA.toString());
System.out.println(studentB.toString());
or in a loop:
for(Student x : studentList)
System.out.println(x.toString());
and so on..
Also, in your code you create a method inside your main method. Of course you will get errors.

Cannot find symbol - method

having hard time calling a method in the main. keeps saying that it cannot find symbol - method addSales(double)
i am doing a project for programming because we just learnt about inheritance and it has 3 super classes and 3 sub classes. i am having a problem with one sub and super class. they are named Hourly and Commission. commission extends hourly. i feel like i have written the method called addSales correctly however when i call it in the main it says that it cannot find the method. am i missing something here? any help would be greatly appreciated.
Commission class:
public class Commission extends Hourly
{
private double totalSales, commission;
public Commission(String eName, String eAddress, String ePhone,
String socSecNumber, double rate, double commissionRate)
{
super(eName, eAddress, ePhone, socSecNumber, rate);
totalSales = 0.0;
commission = commissionRate;
}
public double pay()
{
double payment = super.pay();
payment = (payment + (commission * totalSales));
return payment;
}
public String toString()
{
String result = super.toString();
result += "Total Sales: " + totalSales;
return result;
}
public void addSales(double totalS)
{
totalSales = totalSales + totalS;
}
}
Hourly class:
public class Hourly extends Employee
{
private int hoursWorked;
//-----------------------------------------------------------------
// Sets up this hourly employee using the specified information.
//-----------------------------------------------------------------
public Hourly (String eName, String eAddress, String ePhone,
String socSecNumber, double rate)
{
super (eName, eAddress, ePhone, socSecNumber, rate);
hoursWorked = 0;
}
//-----------------------------------------------------------------
// Adds the specified number of hours to this employee's
// accumulated hours.
//-----------------------------------------------------------------
public void addHours (int moreHours)
{
hoursWorked += moreHours;
}
//-----------------------------------------------------------------
// Computes and returns the pay for this hourly employee.
//-----------------------------------------------------------------
public double pay()
{
double payment = payRate * hoursWorked;
hoursWorked = 0;
return payment;
}
//-----------------------------------------------------------------
// Returns information about this hourly employee as a string.
//-----------------------------------------------------------------
public String toString()
{
String result = super.toString();
result += "\nCurrent hours: " + hoursWorked;
return result;
}
}
main:
public class Firm
{
//--------------------------------------------------------------
// Creates a staff of employees for a firm and pays them.
//--------------------------------------------------------------
public static void main (String[] args)
{
Staff personnel = new Staff(8);
Executive staff0 = new Executive ("Sam", "123 Main Line", "555-0469", "123-45- 6789", 2423.07);
StaffMember staff1 = new Employee ("Carla", "456 Off Line", "555-0101", "987-65-4321", 1246.15);
StaffMember staff2 = new Employee ("Woody", "789 Off Rocker", "555-0000", "010-20-3040", 1169.23);
Hourly staff3 = new Hourly ("Diane", "678 Fifth Ave.", "555-0690", "958-47-3625", 10.55);
Hourly staff6 = new Commission("Marcus Gendron", "66 Highland St.", "272-9555", "123-62-5678", 6.25, 0.20);
Hourly staff7 = new Commission("Joe Dangerous", "55 dude Court", "555-1267", "777-66-5555", 9.75, 0.15);
StaffMember staff4 = new Volunteer ("Norm", "987 Suds Blvd.", "555-8374") ;
StaffMember staff5 = new Volunteer ("Cliff", "321 Duds Lane", "555-7282");
personnel.addStaff(staff0);
personnel.addStaff(staff1);
personnel.addStaff(staff2);
personnel.addStaff(staff3);
personnel.addStaff(staff4);
personnel.addStaff(staff5);
personnel.addStaff(staff6);
personnel.addStaff(staff7);
staff6.addHours(35);
staff6.addSales(400.0);
//error is being shown here ^^^^
staff7.addHours(40);
staff7.addSales(950.00);
staff0.awardBonus (500.00);
staff3.addHours (40);
personnel.payday();
}
}
Both staff6 and staff7 are instances of Hourly. The Hourly class does not have that particular method attached to it.
You would have to declare them as concrete instances of Commission instead.
staff6 is declared as Hourly, and even though it is in fact a Commission, you are trying to access the super class' method.
Declare it as Commission.
I see the object creation below:
Hourly staff6 = new Commission("Marcus Gendron", "66 Highland St.", "272-9555", "123-62-5678", 6.25, 0.20);
addSales method is in the child class Commission. But the type of staff6 is Hourly which is the parent class and Hourly class doesnt have this method. This you dont see the method addsales.
For more detailed understanding, try the following line (which will compile fine). And see what all methods you get
Object staff6 = new Commission("Marcus Gendron", "66 Highland St.", "272-9555", "123-62-5678", 6.25, 0.20);
Here You can only able to call methods that are present on Hourly class.
Because You are referencing Hourly class now as addSales in not present on Hourly class it is not accessible.
Hourly staff6 = new Commission("Marcus Gendron", "66 Highland St.", "272-9555", "123-62-5678", 6.25, 0.20);
In your above code Commission class object have reference to Hourly class. So Commission object will only allowed to access those methods which are Hourly class ( because they are inherited ) and overridden methods of hourly class in commission class.

Having trouble storing data in class constructors, learning OOP

Here is the assignment I"m supposed to complete:
Write a program that models an employee. An employee has an employee number, a name, an address, and a hire date. A name consists of a first name and a last name. An address consists of a street, a city, a state (2 characters), and a 5-digit zip code. A date consists of an integer month, day and year.
Use an Employee class, a Name class, an Address class, and a Date class in your solution.
Your program should prompt the user to enter data for several employees and then display that data. The number of employees to store data for shall be entered from the command line.
What I'm confused about is how to use all the different classes for storing info.
Here is my code (sorry this post is so dang long)
import java.util.Scanner;
public class unitTenDemo
{
public static void main ( String [ ] args )
{
Scanner input = new Scanner ( System.in );
System.out.print ( "Enter the number of employees" );
System.out.println ( "\t" );
int employees = input.nextInt ( );
for ( int count = 0; count < employees; count ++ )
{
System.out.print ( "Enter the employees' numbers" );
int employeeNumber = input.nextInt ( );
System.out.println ( );
System.out.println ( "The number is " +employeeNumber );
System.out.println ( );
}
}
}
//that was the actual output code
//here's the constructor that I'm stuck on
public class unitTen
{
int employeeNumber;
public int Employee ( int empNum )
{
employeeNumber = empNum;
}
string employeeName;
public void Name ( string empName )
{
employeeName = empName;
}
string street;
string city;
string state;
int zipCode;
}
Don't put everything into the constructor. It's okay to write a constructor that builds an object that is not fully initialized. You can organize your program as follows:
Find out how many Employee objects there will be (user input)
Create an array of Employee objects of the appropriate length
For each element of the array, assign a new Employee to that element
For each element of the array, prompt the user for each piece of data needed to properly initialize the Employee.
The last step (which deals with only one Employee at a time) will break down into a lot of details, since each Employee object has a lot of information. Just go through all the elements systematically.
This code won't compile at all. Yopu have declaired int as return type and not returning anything from the method.
public int Employee ( int empNum )
{
employeeNumber = empNum;
}
In addition to the answer pointed to by #Ted , you should modify your Employee class accordingly and then invoke the constructors as you please.
public class Employee // you should change the name of class to Employee
{
int employeeNumber;
public Employee(){}; // default constructor to create empty Employee objects
public Employee ( int empNum ) // constructor cannot have any return type
{
employeeNumber = empNum;
}
string employeeName;
public Employee( string empName, int empNum ) // you can create multiple constructors with different parameters.
{
employeeName = empName;
employeeNumber = empNum;
}
string street;
string city;
string state;
int zipCode;
// you can create getters and setters for these fields
}

Categories