Outputing string values from objects saved in an ArrayList - java

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
}

Related

Unable to print out the desired output

So I am creating a program that reads customer details and order details from two different files. I created methods to read the file, store the data in the object of customers and then add the object of customers into linkedlist.. Now when I try doing the same for order file, I am getting the wrong output. so in the code shown below, I am trying to check if the customer name entered in order file matches the name stored in customer linkedlist.. So say I have two rows in the order.txt file:
Ord101 true James
Ord102 false Jim
with what I have done, I get the following output:
Ord102 false Jim
Ord102 false Jim
instead of getting the correct output which would be:
Ord101 true James
Ord102 false Jim
because both, James and Jim are names present in Customer file and linkedlist. So here is my code for reading order file:
public void readFileOrder() {
Scanner y;
String b,c,d;
LinkedList<Customers> list=new LinkedList<Customers>(); //another method was already created to add data inside list and its working so list contains data
LinkedList<order> list1=new LinkedList<order>();
Boolean isOpen;
order Order1=new order();
while(y.hasNext())
{
b=y.next();
isOpen=y.nextBoolean();
d=y.next();
System.out.println(list);
Customers customers1=new Customers();
for(int i=0;i<list.size();i++) //this is where i'm checking if the customer name in the order file matches the value in list
{
if(list.get(i).getName().equals(d))
{
customers1=list.get(i);
Order1.setCustomer(customers1);
Order1.setName(b);
Order1.setIsOpen(isOpen);
list1.add(Order1);
}
}
}
for(int j=0;j<list1.size();j++)
{
System.out.println(list1.get(j).getCustomer()+" and "+list1.get(j).getName()+" and "+list1.get(j).getIsOpen());
}
}
just in case, provided below are Customer and order class:
import java.util.LinkedList;
public class Customers {
#Override
public String toString() {
return "Customers [Name=" + Name + ", age=" + age + ", email=" + email + ", Address=" + Address + "]";
}
String Name;
int age;
String email;
String Address;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public void removeCustomer(String name2, LinkedList<Customers> list) {
for(int k=0;k<list.size();k++)
{
if(list.get(k).getName().equals(name2))
{
list.remove(list.get(k));
}
}
}
}
order class:
import java.util.LinkedList;
public class order{
String name;
Boolean isOpen;
Customers customer;
String cusName;
public order() {
super();
}
public String getName() {
return name;
}
public order(Customers customer) {
super();
this.customer = customer;
}
public void setName(String name) {
this.name = name;
}
public Boolean getIsOpen() {
return isOpen;
}
public void setIsOpen(Boolean isOpen) {
this.isOpen = isOpen;
}
public String getCustomer() {
return customer.getName();
}
public void setCustomer(Customers customer) {
this.customer=customer;
this.cusName=customer.getName();
}
}
You are adding references to the same order to the list over and over again, each time overwriting the attributes set in the previous iteration of the loop. Instead, create a new order inside the loop.
In other words, change this:
order Order1=new order();
while(y.hasNext()) {
to this:
while(y.hasNext()) {
order Order1=new order();

Print ArrayList(My Datatype) using For Each Loop Not Working

Here is my code of UserDetail class.
public class UserDetail {
public void user_detail() {
Members m1=new Members("Rashid Faheem","0312-6193172","House No. 430, Street No. 5 Mehmood Abad Pindora, Rawalpindi");
Members m2=new Members("Yawar Hayat","0312-6193172", "RajanPur");
Members m3=new Members("Azhar Malik", "0312-6193172", "RajanPur");
Members m4=new Members("Muhammad Ali", "0312-6193172", "RajanPur");
Members m5=new Members("Muhammad Nazik", "0312-6193172", "RajanPur");
ArrayList<Members> al = new ArrayList<Members>();
al.add(m1);
al.add(m2);
al.add(m3);
al.add(m4);
al.add(m5);
System.out.println("These are our Members.");
For (Members m:al) {
System.out.println(m.getName());
}
}
}
Here is code from Members Class which I am using as DataType in ArrayList.
public class Members {
private String name, phone,address;
public Members(String name, String phone, String address) {
name=name;
phone=phone;
address=address;
}
public String getName() {
return name;
}
public String getPhone() {
return phone;
}
public String getAddress() {
return address;
}
}
Update
I changed my code according to your advice but another problem now. I am only getting name but not phone and address.
Output
These are our Members.
Rashid Faheem
Yawar Hayat
Azhar Malik
Muhammad Ali
Muhammad Nazik
for (Members m:al) {
System.out.println(m.getName());
}
Notice the lowercase f. Just a typo.
EDIT:
Your constructor is also just assigning the constructor arguments to themselves. You need to assign the constructor arguments to the class variables.
public Members(String name, String phone, String address) {
this.name = name;
this.phone = phone;
this.address = address;
}
You should replace For by for.
And update Members with additionnal this :
public Members(String name, String phone, String address)
{
this.name=name;
this.phone=phone;
this.address=address;
}
There are two syntax errors. Once you correct them you should be able to print the members list:
for not For.
for (Members m : al) {
System.out.println(m.getName());
}
Members constructor. The code is not assigning the parameters to the member variables.
public Members(String name, String phone, String address) {
this.name=name;
this.phone=phone;
this.address=address;
}
Refer https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
First of all, you should stick to the Java naming conventions - so your method user_detail should be named userDetail. You might want to consider naming it print as that's what it is supposed to do.
Next, the constructor in your Members class does nothing, since you miss the this. as prefix of the left side of your operation. So you would want to write it like this (as mentioned by WatchdogReset):
public Members(String name, String phone, String address) {
this.name = name;
this.phone = phone;
this.address = address;
}
Another problem is the typo in For which is supposed to be for (stated by ninnemank).
I refactored your code, to show you a possible way of doing what you want - of course this is rather opinionated and not a perfect solution.
Members
public class Members {
private String name;
private String phone;
private String address;
public Members(String name, String phone, String address) {
this.name = name;
this.phone = phone;
this.address = address;
}
public String getName() {
return name;
}
public String getPhone() {
return phone;
}
public String getAddress() {
return address;
}
#Override
public String toString(){
return String.join(" / ", this.getName(), this.getPhone(), this.getAddress());
}
}
UserDetail
import java.util.ArrayList;
import java.util.List;
public class UserDetail {
private List<Members> members;
public UserDetail() {
this.members = new ArrayList<>();
}
public boolean addMember(Members member){
return this.members.add(member);
}
#Override
public String toString(){
return this.members.stream()
.map(member -> member.toString())
.reduce((a, b) -> String.join(System.lineSeparator(), a, b))
.orElse("");
}
}
Main
public class Main {
public static void main(String[] args) {
Members m1 = new Members("Rashid Faheem", "0312-6193172", "House No. 430, Street No. 5 Mehmood Abad Pindora, Rawalpindi");
Members m2 = new Members("Yawar Hayat", "0312-6193172", "RajanPur");
Members m3 = new Members("Azhar Malik", "0312-6193172", "RajanPur");
Members m4 = new Members("Muhammad Ali", "0312-6193172", "RajanPur");
Members m5 = new Members("Muhammad Nazik", "0312-6193172", "RajanPur");
UserDetail userDetail = new UserDetail();
userDetail.addMember(m1);
userDetail.addMember(m2);
userDetail.addMember(m3);
userDetail.addMember(m4);
userDetail.addMember(m5);
System.out.println("These are our Members.");
System.out.println(userDetail);
}
}
Output
These are our Members.
Rashid Faheem / 0312-6193172 / House No. 430, Street No. 5 Mehmood Abad Pindora, Rawalpindi
Yawar Hayat / 0312-6193172 / RajanPur
Azhar Malik / 0312-6193172 / RajanPur
Muhammad Ali / 0312-6193172 / RajanPur
Muhammad Nazik / 0312-6193172 / RajanPur

Convert Object to String

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.

Printing the name of an object in Java

I have researched, and although this is a really simple issue, I am not sure how to solve it.
The code I have looks like this:
public class Playlist {
public Playlist(String name) {
}
}
Separate files of course:
#Test
public void CreatePlaylist(){
Playlist myPlaylist = new Playlist("Workout Playlist");
}
I am trying to print the actual name of this new playlist "workout playlist" but I can't seem to find a way to do so.
You need to store the name of your playlist in an instance variable. For instance:
public class Playlist {
private final String name;
public Playlist(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Then you can print it with:
System.out.println(myPlayList.getName());
If you want to make the name mutable, then get rid of the final modifier and add a setName(String) method.
write get method to name or override toString method in the class
public class Playlist {
private String name;
public Playlist (String name) {
this.name = name;
}
public String getName() {
return name;
}
#Override
public String toString() {
return "Playlist [name=" + name + "]";
}
}
Print the name using
System.out.println(playlistObject.getName());
or
System.out.println(playlistObject).
I would prefer setting a getter method over toString() though.
public class Playlist {
private String name;
public Playlist(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Then to show the name:
#Test
public void CreatePlaylist(){
Playlist myPlaylist = new Playlist("Workout Playlist");
System.out.println(myPlaylist.getName());
}
You are not at all storing the 'name' property in your object. So obviously you can't access name. One way is
public class Playlist {
public String name;
public Playlist(String name) {
this.name = name;
}
}
Now you should be able to access your attribute from your testcase like this.
#Test
public void CreatePlaylist(){
Playlist myPlaylist = new Playlist("Workout Playlist");
System.out.println(myPlaylist.name);
}

Is it me or is there a typo in this courseware entry?

I took this from an online MIT courseware discussion (pdf warning):
public class Human {
private String name;
...
public Human(String name) {
this.name = name;
}
public String getName() {
return String;
}
}
public class Student extends Human {
private String username;
public Student(String name, String username) {
super(name);
this.username = username;
}
public String getName() {
return username;
}
public String getRealName() {
return super.getName();
}
}
...
public class World {
...
void someMethod() {
Student alice = new Student("Alice", "abc");
System.out.println(alice.getRealName()); // what gets printed?
Why does getRealName return anything. I know it returns Alice because the constructor is called by super(name) but my question is about:
return String;
Why doesn't getName in the Human class have to be
return name;
It should be. It's a typo. This code as you have pasted it would not compile.
You are correct. It's a typo and should be return name.
Please notify the instructor, or the contact person for the class, so they can update the pdf.
unless the three-dot-area contains something like
private String String = "Alice";
but, nay, I guess it's a typo ;-)

Categories