I am a novice in java having just completed the first year at college and this is my first query on stackoverflow but I have been at this for days.
I want to import name, address and salary in from a txt doc and this is working fine but I am getting the wrong read out once I add it to an arraylist and try to print that out.
Here is my import reader code:
import java.io.*;
import java.util.*;
import java.util.ArrayList;
import java.io.IOException;
import java.io.FileReader;
public class ReadFile{
public static void main(String[] args) throws IOException{
ArrayList<Employee> peopleList = new ArrayList<Employee>();
//Begiining of document import
try {
File myFile = new File("people.txt");
FileReader fileReader = new FileReader(myFile);
BufferedReader bReader = new BufferedReader(fileReader);
String line = null;
while((line = bReader.readLine()) != null){
String[] result = line.split(";");
String name = result[0];
int age = Integer.parseInt(result[1]);
double salary = Double.parseDouble(result[2]);
peopleList.add(new Employee(name,age,salary));
for (Employee token:peopleList)
{
System.out.println(peopleList);
}
}
bReader.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
Here is the contents of people.txt:
Jimmy;32;32000
Paul;28;28000
John;34;45234
Mike;19;19234
and here is the Employee class which is a subclass of Person:
import java.util.*;
public class Employee extends Person implements Comparable<Employee>, PartTimeAble
{
// variables for the Employee class
protected int idNumber;
// ID Number generator
protected static int nextIdNumber = 001;
private double salary = 0.00;
public double extra;
// Constructors for the Employee class
Employee(String name, int age, double salary)
{
// Constructors for the Employee Class
// call superclass form Person class
super(name, age);
idNumber = nextIdNumber++;
this.salary = salary;
}
// Get Salary method
public double getSalary()
{
return salary;
}
// Get ID Number method
public int getIdNumber()
{
return idNumber;
}
// Compare to method Overriding generic Compare
public int compareTo(Employee other)
{
//compare Result for salary
if(salary - other.salary == 0)
{
return 0;
}
else if(salary - other.salary < 0)
{
return -1;
}
else
return 1;
}
// Job method for Employee taken from ParTimeAble Interface
// Works out extra salary for Employee after part time salary
public void doJob(Job j)
{
extra = (j.getPrice()-(j.getPrice()/100*60));
}
public String getDescription()
{
return "Employee, ID:" + idNumber + "\tName: " + super.getName() + " Age: " + super.getAge() + "\tSalary: €" + salary + "\tExtra Fee: €" + Math.round(extra);
}
}
Here is the Person class:
public abstract class Person
{
// variables for the Person class
protected String employeeName = "Don't know";
protected int employeeAge = 0;
// Constructors for the Person class
public Person(String name, int age)
{
employeeName = name;
employeeAge = age;
}
// Get Name
public String getName(){
return employeeName;
}
// Get Age
public int getAge(){
return employeeAge;
}
// Get Description
public abstract String getDescription();
}
and this is the output after compile:
Employee#e86da0
Employee#e86da0
Employee#1754ad2
Employee#e86da0
Employee#1754ad2
Employee#1833955
Employee#e86da0
Employee#1754ad2
Employee#1833955
Employee#291aff
Thank you in advance if anyone can help.
Regards.
Method System.out.println() calls toString() method of the object you pass to it. So by default it prints class_name#address_in_memory. You need to override toString() method for your Employee class. Inside of Employee class:
#Override
public toString(){
return "Employee, ID:" + idNumber + "\nName: " + super.getName() + "\nAge: " + super.getAge() + "\nSalary: €" + salary + "\nExtra Fee: €" + Math.round(extra);
}
(I assume that this is what you want printed?)
Related
I have an assignment but i have problem trying to do some part of it. Appreciate if anyone can give me a hand.
Assignment brief: https://pastebin.com/3PiqvfTE
Main Method: https://pastebin.com/J2kFzB3B
import java.util.ArrayList;
import java.util.Scanner;
public class mainMethod {
public static void main(String[] args) {
//scanner
Scanner scanner = new Scanner (System.in);
//subject object
Subject subject = new Subject (0,null,0);
System.out.println("How many subject do you want to enter: ");
int subjectNumber = scanner.nextInt();
for (int j = 0; j < subjectNumber; j++) {
//subject ID
System.out.println("Please enter the subject ID: ");
int subID = scanner.nextInt();
//subject Name
System.out.println("Please enter subject name: ");
String subName = scanner.next();
//subject fee
System.out.println("Please enter subject fee: ");
double subFee = scanner.nextDouble();
//add subject
subject.addSubject(subID, subName, subFee);
}
//display subject
System.out.println(subject.getSubject());
/*
//loop for part time teacher
System.out.println("Please enter how many part time teacher do you have: ");
int PTcounter = scanner.nextInt();
for (int i = 0; i < PTcounter; i++) {
*/
Teacher teach = new Teacher (0,null,null);
//teacher employee ID
System.out.println ("Please enter the teacher employee ID: ");
int tid = scanner.nextInt();
//teacher name
System.out.println("Please enter the teacher name: ");
String tname = scanner.next();
//teacher gender
System.out.println("Please enter the teacher gender: ");
String tgender = scanner.next();
//add teacher details
teach.addTeacher(tid, tname, tgender);
//display teacher details
System.out.println(teach.getTeacher());
//call address class
Address address = new Address (0,null,null,0);
//address house number
System.out.println("Please enter house number: ");
int addyNum = scanner.nextInt();
//address street name
System.out.println("Please enter street name: ");
String StreetName = scanner.next();
//address city
System.out.println("Please enter city: ");
String City = scanner.next();
//address post code
System.out.println("Please enter postcode: ");
int Postcode = scanner.nextInt();
//add address
address.addAddress(addyNum, StreetName, City, Postcode);
//display address
System.out.println(address.getAddress());
//call Part Time Salary class
PartTimeSalary ptSalary = new PartTimeSalary(0,0);
//max hours
System.out.println("Please enter maximum work hours: ");
int maxHours = scanner.nextInt();
//hourly rate
System.out.println("Please enter hourly rate: ");
double hourlyRate = scanner.nextDouble();
ptSalary.addPTSalary(maxHours, hourlyRate);
System.out.println(ptSalary.getHourlyRate());
//System.out.printf("Teacher details is %s, Subject details is %s, Address is %s", teach.toString(),subject.toString(),address.toString());
}
}
1st problem. I have a subject class and a teacher class. Teacher will be able to teach maximum of 4 subject. I have prompt user to enter subject details before entering teacher details, so when user enter teacher details they will be able to assign subject to teacher just by using the subjectID. I have problem implementing this. My subject is already store in an ArrayList but how to I connect this with teacher. And in the end the program will display what subject each teacher teaches.
Subject Class: https://pastebin.com/iBYFqYDN
import java.util.ArrayList;
import java.util.Arrays;
public class Subject {
private int subjectID;
private String subjectName;
private double fee;
private ArrayList <Subject> subjectList = new ArrayList <Subject>();
public Subject(int subjectID, String subjectName, double fee) {
this.subjectID = subjectID;
this.subjectName = subjectName;
this.fee = fee;
}
public int getSubjectID () {
return subjectID;
}
public void setSubjectID (int subjectID) {
this.subjectID = subjectID;
}
public String getSubjectName () {
return subjectName;
}
public void setSubjectName (String subjectName) {
this.subjectName = subjectName;
}
public double getFee () {
return fee;
}
public void setFee (double fee) {
this.fee = fee;
}
#Override
public String toString() {
return "[subjectID=" + subjectID + ", subjectName=" + subjectName + ", fee=" + fee + "]";
}
public void addSubject (int subjectID, String subjectName, double fee) {
subjectList.add(new Subject(subjectID, subjectName, fee) );
}
public String getSubject () {
return Arrays.toString(subjectList.toArray());
}
}
Teacher class: https://pastebin.com/Np7xUry2
import java.util.ArrayList;
import java.util.Arrays;
public class Teacher {
private int employeeID;
private String name;
private String gender;
private ArrayList <Teacher> teacherDetailsList;
public Teacher (int employeeID, String name, String gender) {
this.employeeID = employeeID;
this.name = name;
this.gender = gender;
this.teacherDetailsList = new ArrayList <Teacher>();
}
public int getEmployeeID () {
return employeeID;
}
public void setEmployeeID (int employeeID) {
this.employeeID = employeeID;
}
public String getName () {
return name;
}
public void setName (String name) {
this.name = name;
}
public String getGender () {
return gender;
}
public void setGender (String gender) {
this.gender = gender;
}
#Override
public String toString() {
return "[employeeID=" + employeeID + ", name=" + name + ", gender=" + gender + "]";
}
public void addTeacher (int employeeID, String name, String gender) {
teacherDetailsList.add(new Teacher (employeeID,name,gender));
}
public String getTeacher () {
return Arrays.toString(teacherDetailsList.toArray());
}
}
2nd problem. Teacher will either be part time or full time teacher. Part time teacher will have a maximum work hour they can work and an hourly rate they will be paid for, so the final salary of part time teacher will be "maximum hours" multiply by "hourly rate". I have store "hourly rate" and "maximum work hours" in an ArrayList but how do I call them to make the multiplication then displaying at the end.
Part time salary class: https://pastebin.com/iGKpu87Y
import java.util.ArrayList;
public class PartTimeSalary {
private int maxHour;
private double hourlyRate;
private double hourlySalary;
private ArrayList <PartTimeSalary> PTSalary = new ArrayList <PartTimeSalary>();
private ArrayList <Double> finalHourlySalary = new ArrayList <Double>();
public PartTimeSalary (int maxHour, double hourlyRate) {
this.maxHour = maxHour;
this.hourlyRate = hourlyRate;
}
public int getMaxHours () {
return maxHour;
}
public void setMaxHour (int maxHour) {
this.maxHour = maxHour;
}
public double getHourlyRate () {
return hourlyRate;
}
public void setHourlyRate (double hourlyRate) {
this.hourlyRate = hourlyRate;
}
public double getHourlySalary() {
hourlySalary = hourlyRate*maxHour;
return hourlySalary;
}
public void addPTSalary (int maxHour, double hourlyRate) {
PTSalary.add(new PartTimeSalary(maxHour,hourlyRate));
}
public void FinalHourlySalary (double hourlySalary) {
hourlySalary = hourlyRate * maxHour;
finalHourlySalary.add(hourlySalary);
}
public ArrayList<Double> getFinalSalary () {
return (new ArrayList <Double>());
}
}
3rd question. I have an address class which is suppose to be part of the Teacher class. I can't seem to connect the address class with teacher class.
Address class: https://pastebin.com/s2HN5p80
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Address {
private int houseNum;
private String streetName;
private String city;
private int postcode;
private List <Address> address = new ArrayList <Address>();
public Address (int houseNum, String streetName, String city, int postcode) {
this.houseNum = houseNum;
this.streetName = streetName;
this.city = city;
this.postcode = postcode;
}
public int getHouseNum() {
return houseNum;
}
public void setHouseNum (int houseNum) {
this.houseNum = houseNum;
}
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 int getPostcode() {
return postcode;
}
public void setPostcode (int postcode) {
this.postcode = postcode;
}
public void addAddress (int houseNum, String streetName, String city, int postcode) {
address.add(new Address (houseNum,streetName,city,postcode));
}
#Override
public String toString() {
return "[houseNum=" + houseNum + ", streetName=" + streetName + ", city=" + city + ", postcode="
+ postcode + "]";
}
public String getAddress () {
return Arrays.toString(address.toArray());
}
}
Thank you 😃😊
Question 1)
Put the "teacherDetailsList" and "subjectList" ArrayLists in the main method, not the consructors. Add the teachers and subjects in main methods, not constructors.
Add a new ArrayList called "mySubjects" as a field for the Teacher Class
Add the following 2 method to the Teacher class:
public Teacher (int employeeID, String name, String gender, ArrayList<Subject> s) {
this.employeeID = employeeID;
this.name = name;
this.gender = gender;
this.mySubjects=s;
}
public Teacher (int employeeID, String name, String gender, Subject s) {
this.employeeID = employeeID;
this.name = name;
this.gender = gender;
this.mySubjects.add(s);
}
public void addSubject(Subject s, boolean b){
if(mySubjects.size()<4)mySubjects.add(s);
else throw OutOfBoundsError;
}
public void removeSubject(Subject s, boolean b){
mySubject.remove(s);
}
public void addSubject(Subject s){
s.changeTeacher(s);
}
public void removeSubject(Subject s){
mySubject.remove(s);
}
Add the following methods & fields to Student class
private Teacher teacher;
public Subject(int subjectID, String subjectName, double fee, Teacher t) {
this.subjectID = subjectID;
this.subjectName = subjectName;
this.fee = fee;
this.setTeacher(t);
}
public void setTeacher(Teacher t){
try{
t.addSubject(this);
teacher=t;
}
catch(OutOfBoundsError e){
System.out.println(t.getName()+" already has a full schedule.");
}
}
public void changeTeacher(Teacher t){
teacher.removeSubject(this);
teacher = t;
t.addSubject(this);
}
Question 2)
make a new double field, constructor parameter (for every constructor in the class), mutator method and accessor mutator called maxHour in the class Subject
add a double field to the teacher class called salary. If the teacher is part-time, set this to 0 in the constructor.
add this method to Teacher class:
public double getSalary(){
if(salary!=0) return salary;
double s=0;
for(Subject i: mySubjects) s+=i.getFee()*i.getMaxHours();
return s;
}
You honestly no longer need the PartTimeSalary class now.
Question 3
make a new Address field, constructor parameter (for every constructor in the class), mutator method and accessor mutator called myAddress in the class Teacher
Don't bother with the ArrayList stuff in your Address Class
I have a super class and 2 subclasses.
My super class is "Employee" with a name and monthlySalary.
My 1st subclass is "Salesman" with an additional instance variable called annualSales.
My2nd subclass is "Executive" with an additional instance variable called called stockPrice.
I have a text file that includes
"year, firstname,lastname, monthlySalary"
"year, firstname,lastname, monthlySalary, annualSales"
"year, firstname,lastname, monthlySalary, stockPrice"
Big question: How do I store the information from my text file into my superclass and two subclasses?
I have this in my main method. After some tips here I tried updating it. Again thank you for the help, I am trying to understand this to succeed. I am very new to programming in general.
public class Project1 {
/**
* #param args the command line arguments
* #throws java.io.FileNotFoundException
*/
public static void main(String[] args) throws IOException {
FileReader fr =new FileReader("C:\\Users\\JakobJundi\\Documents\\NetBeansProjects\\Project1\\src\\project1\\information.txt");
BufferedReader br =new BufferedReader(fr);
String fileLine;
fileLine = br.readLine();
String[] fields = fileLine.split(" ");
Employee employee1 = new Employee(fields[0],Double.parseDouble(fields[1]));
//Salesman salesman1 = new Salesman (fields[0], Double.parseDouble(fields[1]), Double.parseDouble(fields[2]));
//Executive executive1 = new Executive (fields[0], Double.parseDouble(fields[1]), Double.parseDouble(fields[2]));
System.out.println(employee1);
//System.out.println(salesman1);
//System.out.println(executive1);
fields = fileLine.split(" ");
if (fields.length == 2){
Salesman salesman1 = new Salesman(fields[0], Double.parseDouble(fields[1]), Double.parseDouble(fields[2]));
System.out.println(salesman1);
}
}
}
This is my Employee super class:
public class Employee {
final String name;
final double monthlySalary;
private double annualSalary;
public Employee(String name, double monthlySalary) {
System.out.println("Constructing an Employee");
this.name = name;
this.monthlySalary = monthlySalary;
}
#Override
public String toString() {
return "Name: " + name + "--" + "Monthly salary: " + monthlySalary;
}
//getters
public String getName() {
return name;
}
public double getMonthlySalary() {
return monthlySalary;
}
public double getAnnualSalary(){
return monthlySalary * 12;
}
//setters
public void setannualSalary(double newannualSalary) {
annualSalary = newannualSalary;
}
}
And this is one out of my 2 subclasses.
public class Salesman extends Employee {
private final double annualSales; // Annual sales
private double annualSalary;
public Salesman(String name, double monthlySalary, double annualSales) {
super(name, monthlySalary);
this.annualSales = annualSales;
System.out.println("Constructing a Salesman");
}
#Override
public String toString() {
return "Name: " + name + "--" + "Monthly salary: " + monthlySalary;
}
public double getAnnualSales() {
return annualSales;
}
#Override
public double getAnnualSalary(){
return (monthlySalary * 12) + (annualSales * 0.02);
}
#Override
public void setannualSalary(double newannualSalary) {
annualSalary = newannualSalary;
}
}
When running this I get this output:
Constructing an Employee
Name: Jundi,jakob--Monthly salary: 2000.0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at project1.Project1.main(Project1.java:49)
I have class Employe that has variables like id , name ... and 2 other classes that inherit from Employe : Seller and Cashier.
To calculate their salaries, I created a method in each one of Seller and Cashier but I need to access the name via the name getter method in Employe so I'd have :
System.out.println("The salary is "+Seller.getName() +" is : " +salary);
Once I type that, I get an error sayingI need to make the name variable to static, but I need it as non static since I'm creating multiple objects using the name variable.
Any solution to this problem?
EDIT :
This is the Employe class :
public class Employe {
protected int id;
protected String name;
protected String adresse;
protected int nbrHours;
public Employe () {
}
public Employe (int id, String name, String adresse, int nbHours)
{
this.id=id;
this.name=name;
this.adresse=adresse;
this.nbrHours=nbHours;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setNom(String name) {
this.name = name;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
}
This is the Seller class :
public class Seller extends Employe {
private int prime;
public Seller (int id, String name, String adresse, int nbHours,int prime)
{
super(id,name,adresse,nbHours);
this.prime=prime;
}
public int getPrime() {
return prime;
}
public void setPrime(int prime) {
this.prime = prime;
}
#Override
public String toString() {
return super.toString() +" [prime=" + prime + "]";
}
public void salaireSeller ()
{
int salaire = 0;
if(nbrHours<160)
{
salaire = nbrHours * 10 + prime;
System.out.println("La salaire de "+Responsable.getName() +" est : " +salaire);
}
else if(nbrHours >160)
{
int Extra= (160 - nbrHours) * 12;
int salaire1 = 160 * 10000 + prime;
salaire= Extra + salaire1;
System.out.println("La salaire de "+Seller.getName() +" est : " +salaire);
}
}
In the Main class I created a Seller object :
Seller Sel1 = new Seller(2, "Alex", "Miami", 18, 200);
now I want to calculat its salary using the SalaireSeller() method in the Main class of course :
Sel1.salaireSeller();
but in the Seller class :
System.out.println("La salaire de "+Responsable.getName() +" est : " +salaire);
it says I need to set Name to static, this will give every object the same name
You need a Seller instance, to call getName() and getSalary() on.
Seller s = new Seller();
// ...
System.out.println("The salary is " + s.getName() +
" is : " + s.getSalary());
You're certainly trying to access an instance variable from a static method.
What you want to do here is to create an instance of your class, then call the getName() method on the object created.
Seller sell = new Seller();
sell.setName("Jean-Paul"); // This is just an example
System.out.println("His name is " + sell.getName()); // Prints : His name is Jean-Paul
I figuered out a solution, I just need to add the name to the toString() method in class Employee, then add the salary variable to the toString() method in Seller class, without System.out.println(..) in SalaireSeller().
or instead of Seller.getName(), I use this.getName() and it works.
I'm writing code for an application that keeps track of a student’s food purchases at a campus cafeteria. There's two classes - Student, which holds overloaded constructors & appropriate getter & setter methods; and MealCard, which holds a class variable to track the number of meal cards issued, appropriate getter & setter methods, a purchaseItem() method, a purchasePoints() method & an overriddden toString() method. There's a Tester class also.
In my MealCard class, the methods are written but in the Tester when I call them, they don't work correctly. I want to get the itemValue from the user but how do I do this in the MealCard class?
Same goes for the purchasePoints method, how do I get the topUpValue from user in MealCard class?
Code so far is:
public class Student {
// Instance Variables
private String name;
private int age;
private String address;
// Default Constructor
public Student() {
this("Not Given", 0, "Not Given");
}
// Parameterized constructor that takes in values
public Student(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
// Getters and Setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress(){
return address;
}
public void setAddress(String address) {
this.address = address;
}
// toString() to be overriden
#Override
public String toString() {
return "Name: " + this.name + "\n" + "Age: " + this.age + "\n" + "Address: " + this.address;
}
}
`
public class MealCard extends Student {
static int numberOfMealCards;
private final static int DEFAULT_BALANCE = 1000;
private int itemValue;
private int topUpValue;
public int newBalance;
// Getters and Setters
public int getItemValue() {
return itemValue;
}
public void setItemValue(int itemValue) {
this.itemValue = itemValue;
}
public int getTopUpValue() {
return topUpValue;
}
public void setTopUpValue(int topUpValue) {
this.topUpValue = topUpValue;
}
// purchaseItem method for when students buy food
public int purchaseItem() {
newBalance = DEFAULT_BALANCE - itemValue;
return newBalance;
}
// purchasePoints method for students topping up their meal card balance
public int purchasePoints() {
newBalance = DEFAULT_BALANCE + topUpValue;
return newBalance;
}
// Overriden toString method
#Override
public String toString() {
return super.toString() + "Meal Card Balance: " + this.newBalance + "\n" + "Number of Meal Cards: " + numberOfMealCards;
}
}
`
import java.util.Scanner;
public class TestMealCard {
public static void main(String[] args) {
// Create instances of MealCard class
MealCard student1 = new MealCard();
MealCard student2 = new MealCard();
Scanner keyboard = new Scanner(System.in);
System.out.println("Name: ");
student1.setName(keyboard.nextLine());
System.out.println("Age: ");
student1.setAge(keyboard.nextInt());
System.out.println("Address: ");
student1.setAddress(keyboard.nextLine());
System.out.println("Meal Card Balace: ");
student1.newBalance = keyboard.nextInt();
System.out.println("Number of Meal Cards Issued: ");
student1.numberOfMealCards = keyboard.nextInt();
System.out.println("Name: ");
student2.setName(keyboard.nextLine());
System.out.println("Age: ");
student2.setAge(keyboard.nextInt());
System.out.println("Address: ");
student2.setAddress(keyboard.nextLine());
System.out.println("Meal Card Balace: ");
student2.newBalance = keyboard.nextInt();
System.out.println("Number of Meal Cards Issued: ");
student2.numberOfMealCards = keyboard.nextInt();
// Call purchaseItem
student1.purchaseItem();
// Call purchasePoints
student2.purchasePoints();
// Call tString to output information to user
}
}
In order to set the itemValue from the user you need to get get that input from the user using this setItemValue() method.
Ex.
System.out.print("Please enter the item value: ");
student1.setItemValue(keyboard.nextInt());
or
int itemVal = 0;
System.out.print("Please enter the item value: ");
itemVal = keyboard.nextInt();
student1.setItemValue(itemVal);
as for the other method call just call the setter for toUpValue.
Ex.
System.out.print("Please enter the item value: ");
student1.setTopUpValue(keyboard.nextInt());
or
int toUpVal = 0;
System.out.print("Please enter the item value: ");
itemVal = keyboard.nextInt();
student1.setTopUpValue(topUpVal);
Hope that helps =).
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 7 years ago.
I need to be able to print out the Student objects(all variables) in my array list. Is this possible? When i try to print it outputs this sort of thing e.g student.Student#82701e. I think it's hexadecimal or something
This is my code:
package student;
public class Student {
private String studentName;
private String studentNo;
private String email;
private int year;
public Student() {
this.studentName = null;
this.studentNo = null;
this.email = null;
this.year = -1;
}
public Student(String nName, String nNum, String nEmail, int nYr) {
this.studentName = nName;
this.studentNo = nNum;
this.email = nEmail;
this.year = nYr;
}
public void setStudentName(String newStudentName) {
this.studentName = newStudentName;
}
public void setStudentNo(String newStudentNo) {
this.studentNo = newStudentNo;
}
public void setEmail(String newEmail) {
this.email = newEmail;
}
public void setYear(int newYear) {
this.year = newYear;
}
public String getStudentName() {
return studentName;
}
public String getStudentNo() {
return studentNo;
}
public String getEmail() {
return email;
}
public int getYear() {
return year;
}
}
package student;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class studentTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
List<Student> Students = new ArrayList();
Student student1 = new Student();
student1.setStudentName("Bob Marley");
student1.setStudentNo("N0002");
student1.setEmail("student2#student.com");
student1.setYear(2);
Students.add(student1);
Student student2 = new Student();
student2.setStudentName("Bill Harvey");
student2.setStudentNo("N0003");
student2.setEmail("student3#student.com");
student2.setYear(2);
Students.add(student2);
Student student3 = new Student();
student3.setStudentName("John Beans");
student3.setStudentNo("N0004");
student3.setEmail("student4#student.com");
student3.setYear(2);
Students.add(student3);
System.out.println("Add new students: ");
System.out.println("Enter number of students to add: ");
int countStudents = input.nextInt();
for (int i = 0; i < countStudents; i++) {
Student newStudents = new Student();
System.out.println("Enter details for student: " + (i + 1));
System.out.println("Enter name: ");
newStudents.setStudentName(input.next());
System.out.println("Enter Number: ");
newStudents.setStudentNo(input.next());System.out.println("Search by student number: ");
System.out.println("Enter email: ");
newStudents.setEmail(input.next());
System.out.println("Enter year: ");
newStudents.setYear(input.nextInt());
Students.add(newStudents);
}
}
}
Override toString() method in Student class as below:
#Override
public String toString() {
return ("StudentName:"+this.getStudentName()+
" Student No: "+ this.getStudentNo() +
" Email: "+ this.getEmail() +
" Year : " + this.getYear());
}
Whenever you print any instance of your class, the default toString implementation of Object class is called, which returns the representation that you are getting.
It contains two parts: - Type and Hashcode
So, in student.Student#82701e that you get as output ->
student.Student is the Type, and
82701e is the HashCode
So, you need to override a toString method in your Student class to get required String representation: -
#Override
public String toString() {
return "Student No: " + this.getStudentNo() +
", Student Name: " + this.getStudentName();
}
So, when from your main class, you print your ArrayList, it will invoke the toString method for each instance, that you overrided rather than the one in Object class: -
List<Student> students = new ArrayList();
// You can directly print your ArrayList
System.out.println(students);
// Or, iterate through it to print each instance
for(Student student: students) {
System.out.println(student); // Will invoke overrided `toString()` method
}
In both the above cases, the toString method overrided in Student class will be invoked and appropriate representation of each instance will be printed.
You have to define public String toString() method in your Student class. For example:
public String toString() {
return "Student: " + studentName + ", " + studentNo;
}