So, i have a class named Hospital and a method called InsertFolders inside the Hospital class.
Inside the method the user must fill an array(max 5) of examinations (I made a class called Folders where i have the set and get methods for the array).
Now i have created another method called print where i want to print this array.
Note that there is an array of objects which contains the Folders.
ListOfFolders[i].getNameOfFolder(this is the field of the folder's name for example).
Is there a way where i can print the array?
For example when i try ListOfFolders[i].getArrayOfExaminations() it doesn't print the expected examinations.
Just override toString function like:
public class Person{
private int id;
private String firstName;
private String lasrName;
.
.
public Person(){
this.id = 1;
this.firstName = "First Name";
this.lastName = "Last Name";
}
public String toString(){
String str = "";
str += "Person Info: \n";
str += "Id : " + id + "\n";
str += "First Name : " + firstName + "\n";
str += "Last Name : " + lastName + "\n";
....
return str;
}
}
If you would share us your code I would have implement it better, but this is the idea.
Usage:
List<YourClass> list = new ArrayList<YourClass>();
list.add(new Person());
for (YourClass item : list){
System.out.println(item); //here it will automaticly use the overridden toString in your class
}
Output:
Person Info:
Id: 1
First Name
Last Name
Just printing an object prints the reference (~address) to it by default. You need to override the toString() method for the object to make it print the proper value.
If this is the default array in Java, you can loop over the objects in the array with the for(item : array) syntax.
Related
I am trying to print my arraylist but i don't know why my printing does not print line by line of IntegerPair in each index of Adjlist:
private ArrayList<ArrayList<IntegerPair>> AdjList; //outer arraylist
private ArrayList<IntegerPair> storeNeighbour; //inner arraylist
private IntegerPair pair;
This is my snippet:
for (ArrayList<IntegerPair> l1 : AdjList) {
for (IntegerPair n : l1) {
System.out.println( n + "# ");
}
}
The default behavior of ArrayList.toString() is to return a single string containing a (somewhat) beautified list of calls to toString() on each element in the list.
So, long story short: you are almost there; the one thing that is missing:
#Override
public String toString() {
...
within your class IntegerPair.
Like:
public class IntegerPair {
private final Integer first;
private final Integer second;
...
#Override
public String toString() {
return "(" + first + "/" + second ")";
}
or something alike. Without overriding toString() your class will fall back on the default implementation given in java.lang.Object; and that method returns class name + hashcode number (and is thus not so human-readable).
Here :
for (ArrayList<IntegerPair> l1 : AdjList) {
for (IntegerPair n : l1) {
System.out.println( n + "# ");
}
}
You don't differentiate each printed List.
As a result, you will have a series of output without knowing those associated to a same list.
A more readable print would be :
for (ArrayList<IntegerPair> l1 : AdjList) {
System.out.println("ArrayList with :");
for (IntegerPair n : l1) {
System.out.println( n + "# ");
}
}
You don't specify your output. So I don't suppose toString() is or not overridden. If it is not overridden you should either override it to render the String expected here : System.out.println( n + "# ");, or you should specify the content to render here :
System.out.println( n.getOne() + "," + n.getOther() + "# ");
As a side note, toString() is designed for debugging/logging, not for displaying functional messages as an object could be rendered in a way for a case and in another way for other cases.
Sorry for including so much in here I just do not know where to begin as I am new to Java and I am lost on how to Display an Entire List of Friends once I have inputed them into the array. I need to use a for loop to do this.
Add a toString method to your Friend class like:
#Override
public String toString() {
return "Friend [firstName=" + firstName + ", firstAge=" + firstAge + "]";
}
So when you call System.out.println() you will get a human readable format and not the hashcode.
I would also suggest you move the line :System.out.println("\nYou have added the following friends:"); out of the for loop.
You can remove the entry from the list like:
public void removeFriend()
{
System.out.println("Please enter Name of person you would like to remove: ");
String name = input.nextLine();
Iterator<Friend> it = friendList.iterator();
while(it.hasNext()){
Friend f = it.next();
if(f.getName().equals(name)){
it.remove();
}
}
}
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.
I am trying to get this program to get the passwords from an array list.
import java.util.ArrayList;
public class CompanyDatabase {
public ArrayList<Person> getPeople() {
ArrayList<Person> people = new ArrayList<Person>();
String[] u = {"Joe","Stan","Leo","John","Sara","Lauren"};
String[] p = {"pass4321", "asdfjkl", "genericpw", "13579", "helloworld", "companypass"};
for(int j = 0; j < u.length; j++){
Person temp = new Person(u[j],p[j]);
people.add(temp);
}
return people;
}
}
import java.util.ArrayList;
import java.util.Scanner;
public class CompanyDatabaseDriver {
private static Scanner scan = new Scanner( System.in ) );
public static void main(String args[]) {
CompanyDatabase bcData = new CompanyDatabase();
ArrayList<Person> people = bcData.getPeople();
// what i tried
System.out.println(bcData.getPeople());
// also tried this
System.out.println(people.get(1));
}
}
The output is
[Person#1c9b9ca, Person#c4aad3, Person#1ab28fe, Person#105738, Person#ce5b1c, Person#1bfc93a]
or just
Person#1995d80
for the 2nd thing I tried.
The specific number / letter combination seems to change each time the program is run. Is there a way to specify which string to display from the array list?
Override toString() in the Person class
What you are seeing is the String returned by Object's default toString() method which is the name of the class followed by its hashcode. You will want to override this method and give the Person class a decent toString() method override.
e.g.,
// assuming Person has a name and a password field
#Override
public String toString() {
return name + ": " + password; // + other field contents?
}
Edit: if you only want to display one field in your output, then use Dave Newton's good solution (1+).
Yes; print the object property you want to see:
out.println(people.get(0).getFirstName());
the default implementation when you print List is to call toString for all objects in this List. and because you don't override toString method, it will call the default toString from Object class, that will print objects hashCode in hexadecimal notation, so you get this result:
Person#1c9b9ca ( classname#hashcode) , and it can be changed every time you execute the application because this hashcode come from memory address of the object).
so one option, is to override toString in your class
#Override
public String toString() {
return String.format("First name %s, Last name %s", firstName, lastName);
}
and call
System.out.println(yourList); // this will print toString for each object
the other option, is to print these attributes when you iterate on the List
for(Person person: persons) {
System.out.println("Person first name: " + person.getFirstName() + " , Last Name: " + person.getLastName());
}
In the first print statement you are trying to print the object..that is why you always see different number/letter combination..
I'm practicing learning how to write classes and creating "is" relationships between objects. In the code below, the first class "Person" defines a Person, and then in the second class "MarryDemo", I see whether someone is married, who that spouse is, their address, etc. They even get divorced very shortly thereafter. The code is based on the examples of Jan Skansholm Java from the Beginning.
The problem is that I expected the result of the main method in MarryDemo to be "Kris Humphries", "43 New Jersey Jets Street", "null", but instead of the spouse name I got Person#558ee9d6, with the spouse's address and the spouse after divorce remaining as I expected them to be.
What does Person#558ee9d6 signify? Is that the location of the object that is referenced by the name "Kris Humphries"? Why does Person#558ee9d6 appear instead of the name?
//defines a person
public class Person {
//instance variables
private String name, address;
private Person spouse;
//constructor
public Person(string n) {
name = n;
}
//instance methods
public String getName() {
return name;
}
public void marry(Person p) {
spouse = p;
p.spouse = this;
}
public Person isMarriedTo() {
return spouse;
}
... //more methods for returning address, divorcing, etc.
}
//
public class MarryDemo {
public static void main (String[] arg) {
String name1 = "Kim Kardashian";
String name2 = "Kris Humphries";
Person p1 = new Person(name1);
Person p2 = new Person(name2);
p1.marry(p2);
System.out.println(p1.marriedTo());
p2.setAddress("43 New Jersey Jets Drive");
System.out.println(p1.marriedTo().getAddress());
p1.divorce();
System.out.println(p1.marriedTo());
}
}
You need to implement a toString() method (as the default is not suitable). Most IDE will generate one for you.
What does Person#558ee9d6 signify?
The class name and identity of the object. See Object.toString() for the code.
Is that the location of the object that is referenced by the name "Kris Humphries"?
Nothing to do with the name. It is Person.toString() you are calling.
Why does Person#558ee9d6 appear instead of the name?
Where do you say you want the name to be printed instead?
If I replace string with String and use the IDE to generate a toString, the default is
#Override
public String toString() {
return "Person{" +
"address='" + address + '\'' +
", name='" + name + '\'' +
", spouse=" + spouse +
'}';
}
This is obviously not suitable as this will go around forever. You can change it to
#Override
public String toString() {
return "Person{" +
"address='" + address + '\'' +
", name='" + name + '\'' +
", spouse=" + spouse != null ? spouse.getName() : " {none}" +
'}';
}
You're printing the Person object. You can either overwrite the toString() method. e.g
public String toString(){
return this.getName();
}
Or, do
System.out.println(p1.marriedTo().getName());
p.s. isMarriedTo is a bad method name because is is usually used for methods that return boolean, getSpouse would be a much better name
you need to override the toString method. The default behaviour is:
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
So what you are seeing is the class name with a hexidecimal representation of the hashcode appended. How is java supposed to know it should print the name property?
You could put this in your person method to display the name:
#Override
public String toString() {
return this.getName();
}
You are trying to convert an object to a String. This (automatically) uses the toString() method available in the Object class. The result is in the form you described.
If you want to convert it to your own, customized string. You should implement the toString() method yourself. For example:
public String toString() {
return name;
}