This is the class with the toString method
class Person {
final String name;
final String address;
final String phoneNr;
Person(String name, String address, String phoneNr) {
this.name = name;
this.address = address;
this.phoneNr = phoneNr;
}
#Override
public String toString() {
return String.format("%-10s, %-20s, %-10s", name, address, phoneNr);
}
}
Now I need to write this method in a PhoneBookList class that I created earlier. How would i do this?
Just override toString() this in Person class and in Phonebooklist when printing any person object will use toString() values
public class Person {
#Override
public String toString() {
return String.format("%-10s, %-20s, %-10s", name, address, phoneNr);
}
}
public class Phonebooklist {
public static void main(String[] args) {
Person person = new Person("name", "address", "000-000-000"); // if you are using constuctor overloading
System.out.println(person);
}
}
, And if you loop over all nodes in Phonebooklist and use Person's toString format you can do this like this:
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
Node current = head;
while (current != null) {
builder.append(current.person); // this will append person object and use it's toString with this format "%-10s, %-20s, %-10s", name, address, phoneNr
if (current.next != null) builder.append("\n");
current = current.next;
}
return builder.toString();
}
Related
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
}
}
I am trying to write a program which stores information about a person in a linked list. I made a simple person class to store the name, age and addresses in the list. I would also like to store multiple addresses for EACH person, and a fact about the place in another linked list, inside the person class.
So for example, "Tara" can have a home address of "10 Central Ave" and a work address of "5 Willow street" etc. The problem is, I don't know how to have a linked list inside another.
My goal is to check whether the person's name is already on the list, and if so, add another address for them. (So that there is no repeats). I am a beginner and can really use some help.
public class Person {
private String name;
private int age;
public LinkedList <String> adresses;
public Person() {
name = "default";
age = 0;
adresses = new LinkedList<>();
}
public Person(String n, int a) {
name = n;
age = a;
}
public LinkedList<Adress> getAdresses() {
return adresses;
}
public void setAdresses(LinkedList<Adress> adresses) {
this.adresses = adresses;
}
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 toString() {
return name+" "+age+" "+adresses;
}
}
public class Adress {
public String adress;
public String fact;
public Adress(String a, String f) {
adress = a;
fact = f;
}
public String getAdress() {
return adress;
}
public void setAdress(String adress) {
this.adress = adress;
}
public String getFact() {
return fact;
}
public void setFact(String fact) {
this.fact = fact;
}
}
public class Test {
public static void main(String[] args) {
Person Tara = new Person("Tara",35);
Person Judah = new Person("Judah",28);
Person Mark = new Person("Mark",45);
Person Seth = new Person("Seth",23);
LinkedList<Object> tester = new LinkedList<>();
tester.add(Tara);
tester.add(Judah);
tester.addLast(Mark);
tester.addLast(Seth);
System.out.println(tester);
}
}
How is about to use the next classic data structure for your project?
public class Person {
private String name
private int age;
public List<Address> addresses;
//...
}
I have a couple to class in which I'm getting and setting a few things and then finally calling it in my main method. But when I call my class in the main method it just gives me the object instead of name,address and age. I know this structure is very complicated but I want to keep this structure because later on I will be adding a lot of things to this. It would be AMAZING if someone could tell me how to do this. I would really appreciate this. Below is my code for all my classes
This is my first class
public class methodOne
{
public String getName()
{
String name = "UserOne";
return name;
}
public int getAge()
{
int age = 17;
return age;
}
public String getAddress()
{
String address = "United States";
return address;
}
}
This is my second class
public class methodTwo
{
String name;
String address;
int age;
public methodTwo(methodOne objectOne)
{
name=objectOne.getName();
address=objectOne.getAddress();
age=objectOne.getAge();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
This is my third class
public class methodThree {
private methodTwo methodTwoInMethodThree;
private methodOne methodOneInMethodThree;
public methodThree()
{
this.methodOneInMethodThree = new methodOne();
this.methodTwoInMethodThree = new methodTwo(methodOneInMethodThree);
}
public methodTwo getMethodTwoInMethodThree() {
return methodTwoInMethodThree;
}
public void setMethodTwoInMethodThree(methodTwo methodTwoInMethodThree) {
this.methodTwoInMethodThree = methodTwoInMethodThree;
}
}
This is my fourth class which is the method maker
public class methodMaker {
public methodThree brandNewFunction(methodTwo object)
{
methodThree thirdMethod = new methodThree();
thirdMethod.setMethodTwoInMethodThree(object);
return thirdMethod;
}
}
This is my main class which calls methodMaker. What I want to achieve is that when I print the value it should print the name,address and age but instead it just prints trial.methodThree#4de5ed7b
public class mainClass {
public static void main(String args[])
{
methodMaker makerOfMethods = new methodMaker();
methodOne one = new methodOne();
methodTwo object = new methodTwo(one);
System.out.println(makerOfMethods.brandNewFunction(object).toString());
}
}
What you need to do is to override the default implementation of the .toString() method in the objects you want to print out:
#Override
public String toString()
{
return "Name: " + this.name;
}
EDIT:
I do not know exactly where you are printing, and you naming convention doesn't really help out, but from what I am understanding, you would need to implement it in all of you classes since they all seem to be related to each other.
So, in your methodOne class (can also be applied to methodTwo):
#Override
public String toString()
{
return "Name: " + this.name + " Age: " + this.age + " Address: + " this.address;
}
In your methodThree class:
private methodTwo methodTwoInMethodThree;
private methodOne methodOneInMethodThree;
#Override
public String toString()
{
StringBulder sb = new StringBuilder();
if(this.methodTwoInMethodThree != null)
{
sb.append("Method 2:").append(methodTwoInMethodThree.toString());
}
if(methodOneInMethodThree != null)
{
sb.append("Method 1:").append(methodOneInMethodThree.toString());
}
return sb.toString();
}
When you call
MyClass myObject = new MyClass();
System.out.println(myObject);
Implicitly , java calls instead
System.out.println(myObject.toString());
So, if in MyClass, you override toString(), then whatever your toString method returns is what's gonna be printed.
Side note: are you confusing classes and methods? Methods are functions in your classes, classes are wrappers around a bunch of attributes and methods. Your naming is confusing.
try this code:
public class methodTwo
{
String name;
String address;
int age;
public methodTwo(methodOne objectOne)
{
name=objectOne.getName();
address=objectOne.getAddress();
age=objectOne.getAge();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString(){
return name+" "+address+" "+age;
}
}
Are you printing the object using println()?
From the docs, println():
calls at first String.valueOf(x) to get the printed object's string value
This string value is obtained from the object's toString() method, which:
returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', and the unsigned hexadecimal representation of the hash code of the object
So if you want to print anything other than this you have to override the toString() method in your object and return a string containing whatever you want.
Just google "override tostring java" and you will see a ton of examples.
I have a small problem with printing out strings that are stored in an object. The object is stored in an ArrayList.
I have three clases that I use im my program:
Friend Class:
package one;
public class Friend implements InterfaceFriend {
private String name;
private String email;
private String phone;
public Friend(String name, String phone, String email) {
// TODO Auto-generated constructor stub
}
#Override
public String getPhone() {
return phone;
}
#Override
public String getEmail() {
return email;
}
#Override
public String getName() {
return name;
}
#Override
public void setPhone(String phone1) {
phone1 = phone;
}
#Override
public void setEmail(String email1) {
email1 = email;
}
#Override
public void setName(String name1) {
name1 = name;
}
}
FriendInterface:
package one;
public interface InterfaceFriend {
String getPhone(); // Returns phone number.
String getEmail(); // Returns email.
String getName(); // Returns name.
void setPhone(String phone); // Sets phone.
void setEmail(String email); // Sets email.
void setName(String name); // Sets name.
}
and Test Class:
package one;
import java.util.ArrayList;
import java.util.List;
public class FriendTest {
static List<Friend> friends;
static Friend friend;
public static void main(String args[]) {
friends = new ArrayList<Friend>();
friend = new Friend("Jane Doe", "085-5555555", "jane.doe#gmail.com");
friends.add(friend);
friend = new Friend("John Doe", "085-1111111", "john.doe#gmail.com");
friends.add(friend);
friend = new Friend("Paul Weller", "085-3333333", "paul.weller#gmail.com");
friends.add(friend);
System.out.println("Friends added to list:");
System.out.println(friends.toString());
}
}
The problem is that when I am running the System.out.println(friends.toString());from the Test Class i am getting this:
Friends added to list:
[one.Friend#38f0b51d, one.Friend#4302a01f, one.Friend#615e7597]
Instead the Strings with the values that I want. Any help appreciated.
You'll need to override the toString() method in the Friend class as commented already, but you also need to complete the constructor that you're using.
public Friend(String name, String phone, String email) {
this.name = name;
this.phone = phone;
this.email = email;
}
Moreover, the code in your setters are backwards.
In you friend class you need to override toString()
public class Friend implements InterfaceFriend {
...
...
public String toString(){
return name + " " + email + " " + phone; // or whatever format you want printed
}
}
you simply override toString method. place this inside of Friend class. problem solved..
public String toString(){
// return your Strings..
}
Override to toString() in your class, to what output suits you. The reason you're getting that output is because the default toString() provided in objects is a hash code.
public String toString(){
return name; //assuming you only want to display the name else edit it
}
This question already has answers here:
How can I sort a List alphabetically?
(15 answers)
Closed 9 years ago.
I have an array of objects and each objects has a given name and a surname.
These names are written to the object using methods getGivenName and getSurname.
I need to sort the elements in the array in alphabetical order by surname.
how can I do this?
Your comparator
class SampleComparator implements Comparator<YourObject> {
#Override
public int compare(YourObject o1, YourObject o2) {
return o1.getSurname().compareTo(o2.getSurname());
}
}
Your Sorting
Collections.sort(YourList, new SampleComparator())
if you need ignore case then use like
return o1.getSurname().compareToIgnoreCase(o2.getSurname());
Use List rather than using Array. Your class needs to implements Comparable interface.
Please see the code,
By Implementing Comparable interface
public class Person implements Comparable<Person>{
private String givenName;
private String surname;
public static void main(String[] args) {
Person person1 = new Person("a","b");
Person person2 = new Person("c","d");
Person person3 = new Person("e","f");
List<Person> personList = new ArrayList<Person>();
personList.add(person1);
personList.add(person2);
personList.add(person3);
Collections.sort(personList);
System.out.println(personList);
}
#Override
public String toString() {
return "WorkSheet [givenName=" + givenName + ", surname=" + surname
+ "]";
}
public Person() {
// TODO Auto-generated constructor stub
}
public Person(String givenName , String surname) {
this.givenName = givenName;
this.surname = surname;
}
public String getGivenName() {
return givenName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
#Override
public int compareTo(Person o) {
// TODO Auto-generated method stub
return o.getSurname().compareTo(this.getSurname());
}
}
By Implementing Comaparator Interface
public class Person implements Comparator<Person>{
private String givenName;
private String surname;
public static void main(String[] args) {
Person person1 = new Person("a","b");
Person person2 = new Person("c","d");
Person person3 = new Person("e","f");
List<Person> personList = new ArrayList<Person>();
personList.add(person1);
personList.add(person2);
personList.add(person3);
Collections.sort(personList , new Person());
System.out.println(personList);
}
#Override
public String toString() {
return "WorkSheet [givenName=" + givenName + ", surname=" + surname
+ "]";
}
public Person() {
// TODO Auto-generated constructor stub
}
public Person(String givenName , String surname) {
this.givenName = givenName;
this.surname = surname;
}
public String getGivenName() {
return givenName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
#Override
public int compare(Person o1, Person o2) {
// TODO Auto-generated method stub
return o2.getSurname().compareTo(o1.getSurname());
}
}
When sorting natural language texts, it's recommended to use a Collator and CollationKeys. The String.compareTo method mentioned by other answers will compare Strings based on the Unicode value of each character in the strings, which might not be what you want/ expect, depending on your input Strings and locale.
Note that I wrote some utility methods to help sorting natural language texts.
E.g. you coud try something like:
public class PersonLocalizer implements Localizer<Person> {
#Override
public String getDisplayString(Person person, Locale inLocale) {
return person.getSurname();
}
}
[...]
Localizables.sort(new PersonLocalizer (), persons);
Maven:
<dependency>
<groupId>org.softsmithy.lib</groupId>
<artifactId>softsmithy-lib-core</artifactId>
<version>0.3</version>
</dependency>