Output List Is Wrong? - java

I have code like this:
public class Main {
public static void main(String[] args) {
List<Object> arrayList = new ArrayList<Object>();
arrayList.add(new Student("First", "Last", "10"));
System.out.println(arrayList);
}
}
With Student Class is:
public class Student extends Human {
private String grade;
public Student(String first, String last, String gradeValue) {
super(first, last);
this.setGrade(gradeValue);
}
public void setGrade(String grade) {
this.grade = grade;
}
public String getGrade() {
return grade;
}
}
It's will extends from Human Class:
public abstract class Human {
private String firstname;
private String lastname;
public Human(String first, String last) {
this.setFirstname(first);
this.setLastname(last);
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getLastname() {
return lastname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getFirstname() {
return firstname;
}
}
Main ideas is I try to create a list 10 students with FirstName LastName and Grade.
Now when I try to print the list in main method, it's show me this: [Student#6fbae5f5].
What I want it show is: First Last 10.
Please note that I try to add more student to the list and it have to show like this:
FirstName1 LastName1 10
FirstName2 LastName2 3
FirstName3 LastName3 7
......................

Add below code in your Student class
#Override
public String toString() {
return "Student [getFirstname()=" + getFirstname() + ", getLastname()="
+ getLastname() + ", getGrade()=" + getGrade() + "]";
}

Since each object has toString() method, the default is displaying the class name representation, then adding # sign and then the hashcode. In your case, you're printing the object itself.
If you want to print the content of the arrayList, you should loop on it:
for(Student student : arrayList) {
System.out.println(student)
}
That's after you'll override toString in Student.

1.Add this to Human Class:
#Override
public String toString() {
// TODO Auto-generated method stub
return firstname + " " + lastname;
}
2. Add this to Student Class:
#Override
public String toString() {
// TODO Auto-generated method stub
return super.toString() + " " + grade;
}

Related

How to output complete details

I am looking to create a leisure centre booking system in Java, which utilises OOP.
2 of the classes collect names and addresses and membership type, which are added to an ArrayList called memberRegister. How can I print all of the member details (i.e. what is stored in the array list), thus outputting Name, Address, Membertype, etc, all in one command?
My source code for classes in question follows...
public class Name {
private String firstName;
private String middleName;
private String lastName;
//constructor to create object with a first and last name
public Name(String fName, String lName) {
firstName = fName;
middleName = "";
lastName = lName;
}
//constructor to create object with first, middle and last name
//if there isn't a middle name, that parameter could be an empty String
public Name(String fName, String mName, String lName) {
firstName = fName;
middleName = mName;
lastName = lName;
}
// constructor to create name from full name
// in the format first name then space then last name
// or first name then space then middle name then space then last name
public Name (String fullName) {
int spacePos1 = fullName.indexOf(' ');
firstName = fullName.substring(0, spacePos1);
int spacePos2 = fullName.lastIndexOf(' ');
if (spacePos1 == spacePos2)
middleName = "";
else
middleName = fullName.substring(spacePos1+1, spacePos2);
lastName = fullName.substring(spacePos2 + 1);
}
// returns the first name
public String getFirstName() {return firstName; }
// returns the last name
public String getLastName() {return lastName; }
//change the last name to the value provided in the parameter
public void setLastName(String ln) {
lastName = ln;
}
//returns the first name then a space then the last name
public String getFirstAndLastName() {
return firstName + " " + lastName;
}
// returns the last name followed by a comma and a space
// then the first name
public String getLastCommaFirst() {
return lastName + ", "+ firstName;
}
public String getFullname() {
return firstName + " " + middleName + " " + lastName;
}
}
public class Address {
private String first_line, town, postcode;
public Address(String first_line, String town, String pcode)
{
this.first_line = first_line;
this.town = town;
postcode = pcode;
}
public Address()
{
first_line = "";
town = "";
postcode = "";
}
public String getFirst_line() {
return first_line;
}
public void setFirst_line(String first_line) {
this.first_line = first_line;
}
public String getTown() {
return town;
}
public void setTown() {
this.town = town;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
}
public class Member extends Person {
private String id; // membership ID number
private String type; // full, family, exercise, swim, casual
public Member(String id, String type, Name n, Address a)
{
super(n, a);
this.id = id;
this.type = type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
import java.util.ArrayList;
public class Registration {
private ArrayList<Member> memberRegister;
public Registration()
{
memberRegister = new ArrayList();
}
public void register(Member m)
{
memberRegister.add(m);
}
public int countMembers()
{
return memberRegister.size();
}
public Member getMember(int i) {
return memberRegister.get(i);
}
public class Main {
public static void main(String[] args) {
Name n = new Name("Kieran", "David", "Nock");
Address a = new Address ("123 Skywalker Way", "London", "NW1 1AA");
Member m = new Member("001", "Full", n, a);
Registration reg = new Registration();
reg.register(m);
System.out.println(reg.countMembers());
System.out.println(reg.getMember(0).getName().getFullname());
}
}
Hey I would do it in following way
First override toString() methods of all the model classes and remember to override Member class toString() in following way
#Override
public String toString() {
return "Member{" +
"id='" + id + '\'' +
", type='" + type + '\'' +
'}'+super.toString();
}
After this adding the below single line in main method would work
reg.getMemberRegister().stream().forEach(System.out::println);
NOTE: create a getter for memberRegister list which is present in Registration Class

Calling superclass in main method

I've just learned about superclasses and subclasses and the homework is pretty simple: have 2 classes and a test class to call and print the attributes. Below is my code from all 3 classes. My question is, why isn't the department attributes printing in my main? Everything else prints just fine, I just can't get that last little bit to print. I think it has something to do with super...thank you in advance! Second computer course and I'm finally feeling I sort of get it, so that's improvement from the first class I took!
public class Employee {
private String firstName;
private String lastName;
private int employeeID;
private double salary;
public Employee () {
firstName = null;
lastName = null;
employeeID = 0;
salary = 0.00;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getEmployeeID() {
return employeeID;
}
public double getSalary() {
return salary;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setEmployeeID(int employeeID) {
this.employeeID = employeeID;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String employeeSummary () {
String employeeSummary = "Employee's name is: " + getFirstName() + " " + getLastName() +
". The employee's ID number is " + getEmployeeID() +
". The employee's salary is " + getSalary();
System.out.println(employeeSummary);
return employeeSummary;
}
}
public class Manager extends Employee {
private String departmentA;
public Manager() {
super();
departmentA = null;
}
public String getDepartmentA() {
return departmentA;
}
public void setDepartmentA(String departmentA) {
this.departmentA = departmentA;
}
public void EmployeeSummary() {
super.employeeSummary();
System.out.println("The employee's department is " + departmentA);
}
}
public class ManagerDerivation {
public static void main(String[] args) {
Manager person = new Manager();
person.setFirstName("Ron");
person.setLastName("Weasley");
person.setEmployeeID(2345);
person.setSalary(65000.00);
person.setDepartmentA("Department of Magical Law Enforcement");
person.employeeSummary();
return;
}
}
Method names are case sensitive. EmployeeSummary() does not override employeeSummary() because it uses a different name.
To avoid mistakes like this, always include the #Override annotation on overridden methods. If you include that annotation and make a mistake in the method signature, compilation will fail.
Note also that your return types for the two methods are different (String and void). Overridden methods must have compatible return types.
There is some spelling (employeeSummary vs. EmployeeSummary) mistakes and return types dont match, in Employee should be
public void employeeSummary () {
String employeeSummary = "Employee's name is: " + getFirstName() + " " +
getLastName() +
". The employee's ID number is " + getEmployeeID() +
". The employee's salary is " + getSalary();
System.out.println(employeeSummary);
}
then in Manager
public void employeeSummary() {
super.employeeSummary();
System.out.println("The employee's department is " + departmentA);
}

Checking if an object is in arraylist in Java

So here is assignment :
A student entity has a name and an address (both represented by an object of class Name and Address), in addition to a university ID, and a course schedule represented by an ArrayList of Courses
Your code should not allow the creation of Two students with the same university ID
So I'm thinking of using ArrayList to hold a list of student and check if student exists or not before create a new student. sorry, this is my first question so I'm trying my best to explain it:
This is my Address class:
public class Address {
private int streetNumber;
private String streetName;
private String city;
private String state;
private int province;
private String country;
public Address (int streetNumber,String streetName,String city,String state,int province,String country)
{
this.streetNumber=streetNumber;
this.streetName=streetName;
this.city=city;
this.state=state;
this.province=province;
this.country=country;
}
public int getStreetNumber() {
return streetNumber;
}
public void setStreetNumber(int streetNumber) {
this.streetNumber = streetNumber;
}
public String getStreetName() {
return streetName;
}
public void setStreetName(String streetName) {
this.streetName = streetName;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public int getProvince() {
return province;
}
public void setProvince(int province) {
this.province = province;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String toString() {
return " [streetNumber=" + streetNumber + ", streetName=" + streetName
+ ", city=" + city + ", state=" + state + ", province="+province+", country="
+ country + "]";
}
public boolean equals(Address add)
{
if(add==null)
{
return true;
}
if(this.getClass()!=add.getClass())
{
return false;
}
Address address=(Address) add;
return streetNumber==address.streetNumber &&
province==address.province && streetName.equals(address.streetName)
&& city.equals(address.city)&& state.equals(address.state)&& country.equals(address.country);
}
}
This is my Name class
public class Name {
private String firstName;
private String lastName;
private char middle;
public Name (String fiName,String laName, char middle)
{
this.firstName=fiName;
this.lastName=laName;
this.middle=middle;
}
public String getFirst()
{
return firstName;
}
public void setFirst(String first)
{
firstName=first;
}
public String getLast()
{
return lastName;
}
public void setLast(String last)
{
lastName=last;
}
public char getMiddle()
{
return middle;
}
public void setMiddle(char midd)
{
middle=midd;
}
/*public String toString()
{
return "[First Name= "+ firstName +" Last Name "+ lastName+" Middle Name "+ middle +"";
}*/
}
This is my Student class:
public class Student {
private int studentId;
private Name name;
private Address address;
boolean a;
ArrayList<Course> courseSchedule = new ArrayList<Course>();
ArrayList<Student> student=new ArrayList<Student>();
public Student(String fiName,String laName, char middle,int stNumber,String stName,String city,String state,int province,String country,int id)
{
if(student.contains(id))
{
System.out.println("Student cannot be same id");
}
else
{
address= new Address(stNumber,stName,city,state,province,country);
name=new Name(fiName,laName,middle);
this.studentId=id;
student.add();
}
}
public int getID()
{
return studentId;
}
public void setId(int id)
{
this.studentId = id;
}
public ArrayList<Course> getCourseSchedule()
{
return courseSchedule;
}
public void setCourseSchedule(ArrayList<Course> courseSchedule)
{
this.courseSchedule = courseSchedule;
}
public void addCourse(Course c) {
courseSchedule.add(c);
}
public void dropCourse(Course course) {
courseSchedule.remove(course);
}
}
My question is how can you add Student Object into Student ArrayList
and how can I check if the Student Id exists in ArrayList with contains() method
student.contains(id) this line right here it does not seem to be right
I hope im explain my question a little clear now. Sorry for my english also.
You would not keep a list of Student objects within the class for Student. Your ArrayList<Student> student=new ArrayList<Student>(); does not belong there.
You would have another structure or collection kept elsewhere named something like StudentBody. When a student is instantiated, it is added to the StudentBody collection.
List< Student > studentBody = new ArrayList< Student >() ; // This list is stored somewhere else in your app.
You could loop a List of Student objects in the StudentBody object. For each you would access the UniversityId member field and compare to your new one being added.
Or you could use a Map, where the key is a UniversityId object and the value is a Student object. Check for an existing key before adding.
These solutions ignore the important issue of concurrency. But that is likely okay for a homework assignment in a beginning course in programming.
Use A HashMap() for collecting information based on unique Ids.
public class Student {
private int studentId;
private Name name;
private Address address;
private static HashMap<Integer,Student> students = new ConcurrentHashMap<>(); // Make a static Map so all objectrs shared same data
public Student(String fiName,String laName, char middle,int stNumber,String stName,String city,String state,int province,String country,int id)
{
if(students.contains(id))
{
System.out.println("Student can be same id");
}
else
{
address= new Address(stNumber,stName,city,state,province,country);
name=new Name(fiName,laName,middle);
this.studentId=id;
students.put(id,this); // use this to add current object
}
}

My toString() is returning only one object times the number of the total object

Can someone help solving this. I want to print all the object once please
public class Student {
private static String firstName;
private static String lastName;
private static int studentId;
private static String major;
private static double balance;
public Student (String fName, String lName,int id,String mjr,double blce) {
firstName = new String(fName);
lastName = new String(lName);
studentId = id;
major = new String(mjr);
balance = blce;
}
public String toString () {
return firstName + "\t" + lastName + "\t" + studentId + "\t" + major + "\t$" + balance;
}
public boolean equals (Object obj) {
if (obj instanceof Student) {
Student collegeStud = (Student) obj;
return (this.firstName.equals(collegeStud.firstName));
} else
return false;
}
public static String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public static String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public static int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public static String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
public static double getBalance() {
return balance;
}
/*
* .commmm
*/
public void setBalance(double balance) {
this.balance = balance;
}
public static void main (String[] args) {
Student Mike = new Student ("Mike","Versace", 99, "CS",0.00);
Student John = new Student ("John","Sling" ,97, "Maths", 20.00);
Student Bob = new Student ("Bob","Tomson" ,57, "Physic",5.00);
System.out.println (Mike.toString() + "\n" + John.toString());
if (Mike.equals(John))
System.out.println ("Mike is John");
else
System.out.println ("Mike is NOT John");
}
}
import java.io.ObjectInputStream.GetField;
public class StudentList {
private int numberOfStudents=0;
private Student[] studentListArray;
//private int studentCount = 0;
StudentList () {
numberOfStudents=0;
studentListArray = new Student[100];
}
public void createStudent(String firstName, String lastName,int studentId, String major, double balance){
Student collegeStud = new Student(firstName, lastName, studentId, major, balance);
addStudent(collegeStud);
numberOfStudents++;
}
public void addStudent (Student collegeStud) {
studentListArray[numberOfStudents++]=new Student(collegeStud.getFirstName(), collegeStud.getLastName(),
collegeStud.getStudentId(), collegeStud.getMajor(),collegeStud.getBalance());
}
public String toString() {
String result = "";
for (int i=0; i<numberOfStudents; i++) {
result += studentListArray[i].toString() + "\n";
}
return result;
}
public Student[] getList() {
return studentListArray;
}
public int listSize() {
return numberOfStudents;
}
public Student searchForStudent (String firstName){
int index = 0;
while (index < numberOfStudents) {
if (studentListArray[index].equals(new Student(Student.getFirstName(),Student.getLastName(),Student.getStudentId(),Student.getMajor(),Student.getBalance()))) {
return studentListArray[index];
}
index++;
}
return null;
}
public static void main(String args[]) {
StudentList theList = new StudentList();
theList.addStudent (new Student ("John","Sling" ,97, "Maths", 20.00));
theList.addStudent (new Student ("Mike","Versace", 99, "CS",0.00));
theList.addStudent (new Student ("Bob","Tomson" ,57, "Physic",5.00));
//theList.createStudent(new Student(Student.getFirstName(),Student.getLastName(),Student.getStudentId(),Student.getMajor(),Student.getBalance()));
//theList.searchForStudent(new String());
System.out.println (theList.toString());
}
}
The problem is that you marked your fields as static. Remove it and the method will work as expected.
public class Student {
//non-static fields
private String firstName;
private String lastName;
private int studentId;
private String major;
private double balance;
//similar for getters, setters and toString method
}
Static members are shared amongst all objects in a class rather than being one per object. Hence each new object you create is overwriting the data of the previous one.
More info:
What does the 'static' keyword do in a class?

Object creation across multiple files (Java)

so I have 2 files called Employee.java and Write.java (These two are within the same package). Say within Employee.java I have
public class Employee {
private String firstName = "test";
private String lastName = "ing";
public Employee(String first, String last) {
firstName = first;
lastName = last;
}
public Employee(Employee copy) {
firstName = copy.firstName;
lastName = copy.lastName;
}
}
Then within my Write.java I want to create an object of type Employee called temp. Like
public void obtainInfo(Employee temp) {
String firstName = temp.firstName;
String lastName = temp.lastName;
}
However I get an error that tells me that it cannot find the symbol in the line that is.
public void obtainInfo(Employee temp) {
I was just wondering where I went wrong that I can't create an object within different files. Despite them being in the same package I can't access them?
I want to be able to incorporate this later on to help me build a text file from reading an array list, but I figured to first start with reading a single line from an object.
It sounds to me that you are trying to set something up so that you can make a copy of an Employee and be able to write the properties to a text file. This won't write to a text file but I think it may clear some things up for you.
public class Employee {
private String firstName;
private String lastName;
public Employee(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public Employee(Employee copy) {
firstName = copy.firstName;
lastName = copy.lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("Employee");
sb.append("{firstName='").append(firstName).append('\'');
sb.append(", lastName='").append(lastName).append('\'');
sb.append('}');
return sb.toString();
}
}
TestClass.java
public class TestClass {
public static void main(String[] args){
//First we have to have one to copy
Employee emp = new Employee("Joe", "Dirt");
//Now we have a copy
Employee emp2 = new Employee(emp);
//Calls the Employee.toString() method and sends it to System.out
System.out.println("Employee 1 : " + emp);
System.out.println("Copy of Employee 1 : " + emp2);
}
}
Make sure that Write.java's class has the same level of access as Employee (IE: Public). If this is not the issue, I would show the code from Write.java specifically as that is most likely where the problem is coming from.

Categories