Printing out all the objects in array list [duplicate] - java

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;
}

Related

How to print an ArrayList? - java

Question will be below.
public class University {
ArrayList<Student> students;
public University() {
students = new ArrayList<Student>();
}
public void addStudent(Student students) {
this.students.add(students);
}}
public class Student {
String name;
String studentID;
static int studentNumber = 0;
Student(String name, String sID){
this.name = name;
this.studentID = sID;
studentNumber++;
}}
public class TestUniversity {
public static void main(String[] args) {
University universityRegister = new University();
Student studentRegister = new Student("Rachel Green", "a1234");
universityRegister.addStudent(studentRegister);
studentRegister = new Student("Monica Geller", "a12345");
universityRegister.addStudent(studentRegister);
studentRegister = new Student("Ross Geller", "a1111");
universityRegister.addStudent(studentRegister);
System.out.println("Number of student in University: " + Student.studentNumber);
}}
A. I created 3 classes, 1.Student, 2.University, 3.UniversityTester, in 3 different files.
B. I created 3 objects of type Studnet, and stored them in the University class as an ArrayList.
I would like to know how I can print the ArrayList of the students including all information from the UniversityTester class? In the future, I will create another object called Stuff and I will store it in the University class as an ArrayList stuffList. Therefore, I don't want to print the students list from class Student.
Override toString() method in Student class as follows:
import java.util.StringJoiner;
public class Student {
String name;
String studentID;
static int studentNumber = 0;
Student(String name, String sID) {
this.name = name;
this.studentID = sID;
studentNumber++;
}
#Override
public String toString() {
return new StringJoiner(", ", Student.class.getSimpleName() + "[", "]")
.add("name='" + name + "'")
.add("studentID='" + studentID + "'")
.toString();
}
}
Now you can print the array list as follows in TestUniversity:
System.out.println("Student Details: " + universityRegister.students);
Add this to your student class:
#Override
public String toString() {
return String.format("Student: %s , StudentID: %s", name, studentID);
}
And then you can print the entire array like this:
System.out.println("Students: " universityRegister.students);
//Or like this:
for(Student st: universityRegister.students){
System.out.println(st);
}

generating groups from txt file and generating them based on preferences

I am designing a group generator that takes in preferences such as “mix gender”, “mix nationality”... I am putting a list of student names, followed by nationality and gene set, in an arraylist. What is the easiest way to generate groups, based on user input, that each group consists of people from different nationalities, or balanced gender.
public ArrayList<String> readEachWord(String className)
{
ArrayList<String> readword = new ArrayList<String>();
Scanner sc2 = null;
try {
sc2 = new Scanner(new File(className + ".txt"));
} catch (FileNotFoundException e) {
System.out.println("error, didnt find file");
e.printStackTrace();
}
while (sc2.hasNextLine()) {
Scanner s2 = new Scanner(sc2.nextLine());
while (s2.hasNext()) {
String s = s2.next();
readword.add(s);
}
}
return readword;
}
I am using this to read a text file, and on each line, I have each student's name nationality and gender. I put them into an ArrayList and am right now trying to figure out how to evenly distribute them based on the user-desired group numbers.
I am using a txt file to store all the information since this group generator is customized for my school.
You can use the groupinBy method
basic tutorial
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
class Scratch {
public static void main(String[] args) {
String student1 = "Macie American Female";
String student2 = "Yago Brazilian Male";
String student3 = "Tom American Male";
List<String> students = Arrays.asList(student1, student2, student3);
System.out.println(groupByGender(students));
System.out.println(groupByNationality(students));
}
private static Map<String, List<Student>> groupByNationality(List<String> students) {
return students.stream().map(s -> mapToStudent(s)).collect(Collectors.groupingBy(Student::getNationality));
}
private static Map<String, List<Student>> groupByGender(List<String> students) {
return students.stream().map(s -> mapToStudent(s)).collect(Collectors.groupingBy(Student::getGender));
}
private static Student mapToStudent(String s) {
String[] ss = s.split(" ");
Student student = new Student();
student.setName(ss[0]);
student.setNationality(ss[1]);
student.setGender(ss[2]);
return student;
}
private static class Student {
String name;
String nationality;
String gender;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNationality() {
return nationality;
}
public void setNationality(String nationality) {
this.nationality = nationality;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
#Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", nationality='" + nationality + '\'' +
", gender='" + gender + '\'' +
'}';
}
}
}
First of all, it would be better if you put your while loop inside the try block because you don't want to get there if the file hasn't been found.
Second, you don't need to create a new instance of Scanner just to read every line. You can simply read your file word by word:
while (sc2.hasNext())
readword.add(sc2.next());
To group the students according to their nationality, you can do something like that:
String nationality = [UserInput] ;
List<String> group = new ArrayList<>();
for (int i = 0; i < readword.size(); i++)
if (readword.get(i + 1).equals(nationality)
group.add(readword.get(i));

Displaying inputs using methods in java

I copied this code in a book I found in the internet about Data Structures and Algorithm in Java. This is the code:
//GameEntry Class
public class GameEntry
{
protected String name;
protected int score;
public GameEntry(String n, int s) {
name = n;
score = s;
}
public String getName() { return name; }
public int getScore() { return score; }
public String toString() {
return "(" + name + ", " + score + ")";
}
}
//Scores Class
public class Scores
{
public static final int maxEntries = 10;
protected int numEntries;
protected GameEntry[] entries;
public Scores(){
entries = new GameEntry[maxEntries];
numEntries = 3;
}
public String toString() {
String s = "[";
for(int i=0; i<numEntries; i++) {
if(i > 0) {
s = s + ", ";
}
s = s + entries[i];
}
return s + "]";
}
public static void main(String[] args){
Scanner input = new Scanner(System.in);
Scores s = new Scores();
for(int i=0; i<s.numEntries; i++){
System.out.print("Enter Name: ");
String nm = input.nextLine();
System.out.print("Enter Score: ");
int sc = input.nextInt();
input.nextLine();
s.entries[i] = new GameEntry(nm, sc);
System.out.println(s.toString());
}
}
}
This runs well like what it said in the book. It outputs:
//just an example input
[(John, 89), (Peter, 90), (Matthew, 90)]
What I don't understand is how did the names inside the parenthesis which is made in the GameEntry Class inside its toString() method (John, 89) is being outputted and yet what I written inside the System.out.println(s.toString); in Scores Class only pertains to the toString method in its own class?
I am expecting that the brackets in the toString() method in the Scores Class will be outputting only the brackets "[]" for it is the only one that I called in the main method... Can anyone please explain this to me how did this happened? I am little bit new in Java Data Structures.
Another thing I try to do this in a different sample program following the concept of what I see in the book..
This my codes:
//FirstClass
public class FirstClass
{
protected String name;
protected int age;
protected FirstClass(String n, int a) {
name = n;
age = a;
}
public String getName() { return name; }
public int getAge() { return age; }
public String printData() {
return "My name is: " + name + ", I am " + age + " years old";
}
}
//Second Class
import java.util.Scanner;
public class SecondClass
{
protected FirstClass f;
private static String nm;
private static int ag;
public SecondClass() {
f = new FirstClass(nm, ag);
}
public String toString(){
return "(" + f + ")";
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
SecondClass s = new SecondClass();
System.out.print("Enter Name: ");
nm = input.nextLine();
System.out.print("Enter Age: ");
ag = input.nextInt();
input.nextLine();
s.f = new FirstClass(nm, ag);
System.out.println(s.toString());
}
}
//Sample Input
Enter Name: John
Enter Age: 16
The output of this is:
(FirstClass#7cc7b1d2)
What I am expecting is:
("My name: is John, I am 16 years old")
What is my error in this???

Calling methods from different classes | Java

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 =).

Adding contents from an imported document to an arraylist

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?)

Categories

Resources