Printing elements of list of objects [duplicate] - java

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 3 years ago.
//contacts class
package com.company;
public class Contacts {
private String name;
private String number;
public Contacts(String name, String number) {
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
public String getNumber() {
return number;
}
}
//class Phone
package com.company;
import java.rmi.StubNotFoundException;
import java.util.ArrayList;
public class Phone {
private ArrayList<Contacts> contacts1 = new ArrayList<Contacts>();
public void addContact(String name, String numbers) {
Contacts contacts = new Contacts(name, numbers);
contacts1.add(contacts);
}
public void printContacts() {
for (int i = 0; i < contacts1.size(); i++) {
System.out.println(contacts1.); // >>> how to print elements (name and phone number)
}
}
}
Here I tried to print a list of contacts including name and phone number but could not handle how to iterate over a list of objects. How can I print name and phoneNumber using printContacts() method in Phone class?
Thanks

You would do:
System.out.println(contacts1.get(i));
but that would just give Contacts#somenumber, so you will need to add a toString() method to the Contacts class.
In the contacts class, add a function that looks like this:
#Override
public String toString() {
return name + ": " + number;
}

Override toString method in your class Contacts to return a string representation of your class object (for e.g. json string). System.out.println prints string returned by this method.
public class Contacts {
private String name;
private String number;
...
#Override
public String toString() {
return "{\"name\": \"" + name + "\", \"number\": \"" + number + "\"}";
}
}
P.S. If you are using one the java IDEs, check out the implementation of println method in file PrintStream.java in java source code. Java IDEs provides this feature of code navigation in your project by which you can actually navigate through source code of Java itself.

Related

Java Exarcise. How to create a class similar to social media site?

Create and implement a class Person. A Person has a firstName and friends. Store the names of the friends as a String, separated by spaces. Provide a constructor that constructs a Person with a given name (passed through arguments) and no friends. Provide the following methods:
public void befriend(Person p)
public void unfriend(Person p)
public String getFriendNames()
public int getFriendCount()
*Hint - you can use p.name to access the name of the Person passed to a method as an argument.
Include a Tester class to make sure your Person has some friends.
How do I store the names of the friends as a String, separated by spaces. (I have to be able to input the names from the main method). I also have no idea how to get rid of already inputted name using the method "unfriend"
public class Person
{
private String firstName;
private String friendNames;
private int friendCount;
public Person(String name)
{
firstName = name;
friendCount = 0;
}
public String getFriendNames()
{
return friendNames;
}
public double getFriendCount()
{
return friendCount;
}
public void befriend(String name)
{
friendNames = friendNames + " " + name;
friendCount++;
}
public void unfriend(String name)
{
String[] parseNames = friendNames.split(name);
friendNames = parseNames[0] + parseNames[1];
friendCount--;
}
}
Main Method:
public class PersonTester {
public static void main(String[] args) {
Person p = new Person("Alex");
p.befriend("John");
p.befriend("Alice");
p.befriend("Mike");
p.befriend("Annette");
p.unfriend("Alice");
System.out.println(p.getFriendCount());
System.out.println(p.getFriendNames());
}
}
Expected output:
2
John Mike
The problems you are having with the methods using the parameter(Person p) are because you have two different variables: friendName (which exists) and name (which does not). Changing the variable friendName to name will take care of some of the errors you are receiving.
(Also the method getFriendCount() returns friendsCount, but should return friendCount (you have an extra s in there) and your assignment calls for a method called befriend, not bestFriend.)
How to delete friends:
You can delete a friend by parsing the friend out of the friendNames string and then concatenating the two resulting strings back together:
public void unfriend(String name)
{
String[] parseNames = friendNames.split(name);
friendNames = parseNames[0] + parseNames[1];
friendCount--;
}
I would suggest changing befriend and unfriends parameters to accept a String instead of a Person object. Person already has access to its own object and in your main you are trying to pass them Strings anyways. Here is what befriend should look like:
public void befriend(String name) //Changed to "befriend"
{
friendNames = friendNames + " " + name;
friendCount++;
}
Also, you only need one constructor for Person, which should look like this:
public Person(String name)
{
firstName = name;
friendCount = 0;
}
When I run your program (using these changes) I get the following output:
2.0
John Mike

how can I return a String?

package book1;
import java.util.ArrayList;
public abstract class Book {
public String Book (String name, String ref_num, int owned_copies, int loaned_copies ){
return;
}
}
class Fiction extends Book{
public Fiction(String name, String ref_num, int owned_copies, String author) {
}
}
at the moment when i input values into the variable arguments and call them with this :
public static class BookTest {
public static void main(String[] args) {
ArrayList<Book> library = new ArrayList<Book>();
library.add(new Fiction("The Saga of An Aga","F001",3,"A.Stove"));
library.add(new Fiction("Dangerous Cliffs","F002",4,"Eileen Dover"));
for (Book b: library) System.out.println(b);
System.out.println();
}
}
i get a return value of this:
book1.Fiction#15db9742
book1.Fiction#6d06d69c
book1.NonFiction#7852e922
book1.ReferenceBook#4e25154f
how can i convert the classes to return a string value instead of the object value? I need to do this without changing BookTest class. I know i need to use to string to convert the values. but i don't know how to catch the return value with it. could someone please point me in the right direction on how to convert this output into a string value?
You need to overwrite the toString() Method of your Book class. In this class you can generate a String however you like. Example:
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(this.author).append(": ").append(this.title);
return sb.toString();
}
You need to override the toString() method in your Book or Fiction class. The method is actually declared in the Object class, which all classes inherit from.
#Override
public String toString(){
return ""; // Replace this String with the variables or String literals that you want to return and print.
}
This method is called by System.out.println() and System.out.print() when they receive an object in the parameter (as opposed to a primitive, such as int and float).
To reference the variables in the method, you'll need to declare them in the class and store them via the class's constructor.
For example:
public abstract class Book {
private String name;
private String reference;
private int ownedCopies;
private int loanedCopies;
public Book (String name, String reference, int ownedCopies, int loanedCopies) {
this.name = name;
this.reference = reference;
this.ownedCopies = ownedCopies;
this.loanedCopies = loanedCopies;
}
#Override
public String toString(){
return name + ", Ref:" + reference + ", OwnedCopies: " + ownedCopies + ", LoanedCopies: " + loanedCopies; // Replace this String with the variables or String literals that you want to return and print.
}
}
The classes you have defined, don't store any values. It is in other words useful to construct a new book. You need to provide fields:
public abstract class Book {
private String name;
private String ref_num;
private int owned_copies;
private int loaned_copies;
public String Book (String name, String ref_num, int owned_copies, int loaned_copies) {
this.name = name;
this.ref_num = ref_num;
this.owned_copies = owned_copies;
this.loaned_copies = loaned_copies;
}
public String getName () {
return name;
}
//other getters
}
Now an object is basically a set of fields. If you want to print something, you can access and print one of these fields, for instance:
for (Book b: library) System.out.println(b.getName());
In Java, you can also provide a default way to print an object by overriding the toString method:
#Override
public String toString () {
return ref_num+" "+name;
}
in the Book class.
Need to give your object Book a ToString() override.
http://www.javapractices.com/topic/TopicAction.do?Id=55
Example:
#Override public String toString()
{
return name;
}
Where name, is a string in the Class.
I am hoping that you have assigned the passed arguments to certain attributes of the classes. Now, once you are done with that, you can override the toString() method in Book to return your customized string for printing.

Java: beginner help getting variable

This is for a school project. I have built a simple class with 3 string variables and a constructor to fill these fields.
public class Names {
String firstName;
String middleName;
String lastName;
public Names(String name){
System.out.println("Passed name is: " + name);
}
public void setFirstName(String name){
firstName = name;
}
public void setMiddleName(String name){
middleName = name;
}
public void setLastName(String name){
lastName = name;
}
public static void main(String []args){
Names drew = new Names("Drew");
drew.setFirstName("Drew");
drew.setMiddleName("Leland");
drew.setLastName("Sommer");
System.out.println(drew.firstName + " " + drew.middleName + " " + drew.lastName);
}
public getFirstName(String name){
}
public getMiddleName(String name){
}
public getLastName(String name){
}}
At the bottom where it is getFirstName, getMiddleName, getLastName I want to be able to pass something like getFirstName(drew) and have it return drew.firstName?
I am very new to java FYI.
These are "getter" methods to return the values of instance fields. drew is your current Names instance here, therefore if you call these methods on this instance, you'll receive the values you've set with your "setter" methods. And since you're calling them on a specific instance, you don't need to pass it as a method argument. That is why these getter methods are normally parameterless.
They should look like this:
public String getFirstName() {
return firstName;
}
public String getMiddleName() {
return middleName;
}
public String getLastName() {
return lastName;
}
Please note that I've added the corresponding return type (String), because the data type of each instance field is String.
Your println call in the main method would then look like this:
System.out.println(drew.getFirstName() + " " + drew.getMiddleName() + " " + drew.getLastName());
public String getFirstName() {
return this.firstName;
}
This will return the firstName of the object you call it on.
You can call it like this:
System.out.println(drew.getFirstName() + " " + drew.middleName + " " + drew.lastName);
You can then do the same thing for getMiddleName and getLastName.
Your get methods will be called by an instance of your Names class. When you create an instance of the class and assign it a variable name, just use that variable name to call the method and it will return the name for that instance.
//Instantiate the Names class
Names drew = new Names("Drew");
//Call methods to set the names
drew.setFirstName("Drew");
drew.setMiddleName("John");
drew.setLastName("Smith");
//Call methods to get the names
drew.getFirstName(); //Returns "Drew"
drew.getMiddleName(); //Returns "John"
drew.getLastName(); //Returns "Smith"
And, like others suggested, your get / set methods should be like this:
public void setFirstName(String n){
firstName = n;
}
public String getFirstName(){
return firstName;
}
as you said, "I want to be able to pass something like getFirstName(drew) and have it return drew.firstName"
so the impl is simple,
public String getFirstName(Names other) {
return other.firstName;
}

Java code output is weird? [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed last month.
I do not understand why my output is not what I expected, instead of showing the persons information, the output displays: examples.Examples#15db9742
Am I doing something wrong in my code?
package examples;
public class Examples {
String name;
int age;
char gender;
public Examples(String name, int age, char gender){
this.name = name;
this.age = age;
this.gender = gender;
}
public static void main(String[] args) {
Examples[] person = new Examples[10];
person[0] = new Examples("Doe",25,'m');
System.out.println(person[0]);
}
}
Add a toString() method to your class:
public class Examples {
String name;
int age;
char gender;
public Examples(String name, int age, char gender){
this.name = name;
this.age = age;
this.gender = gender;
}
#Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append(this.name + " ");
result.append(this.age + " ");
result.append(this.gender + " ");
return result.toString();
}
public static void main(String[] args) {
Examples[] person = new Examples[10];
person[0] = new Examples("Doe",25,'m');
System.out.println(person[0]);
}
}
When you say
System.out.println(person[0]);
java doesn't automatically know what you want printed out. To tell it, you write a method in your Examples class called toString() which will return a string containing the info you want. Something like:
#Override
public String toString() {
return "Name: " + name +
" Age: " + String.valueOf(this.age) +
" Gender: " + String.valueOf(this.gender);
}
Java has no way of knowing what you want it to print. By default, the toString() method is called when you use System.out.println() with an object.
Your Examples class should have its own toString() method so you can decide what to print. The default toString() returns a representation of the object in memory.
For example, to print out the object's name:
package examples;
public class Examples {
...
#Override
public String toString() {
return name;
}
}
Your output is right, when you print an object the method toString() of the object is called; by default it returns what you see (the class and a memory direction).
Override the method toString() of the class to make him return a descriptive String. E.g.:
public class Examples {
// The same ...
public String toString(){
return "My name is " + name + " and I have " + age + " years."
}
// The same ...
}
If you do that you will get a more descriptive String when calling toString() and so when printing an object of class Examples.
New output is
My name is Dow and I have 25 years.
person is an array of type Examples, so by acessing person[0] you are telling it to print an Examples instance. Since the Examples class does not implement an toString() method it will call the parent Object.toString() method that produces the output you are seeing.
Add the following method to your Examples class
public String toString() {
return "[name="+this.name+", age="+this.age+", gender="+this.gender+"]";
}
You have explicitly to create a method which outputs the persons data or override the toString() method to do the same thing:
public class Person
{
String name;
int age;
char gender;
public Person(String name, int age, char gender)
{
this.name = name;
this.age = age;
this.gender = gender;
}
//Override the toString() method
//is a usual programming technique
//to output the contents of an object
public String toString()
{
return "Name: " + this.name + "\nAge: " + this.age + "\nGender: "
+ this.gender;
}
//You can also write something like this
public void showInfo()
{
System.out.printf("Persons Info:\n\nName: %s\nAge: %s\nGender: %s", this.name, this.age, this.gender);
}
public static void main(String[] args)
{
Person p = new Person("bad_alloc", 97, 'm');
//System.out.println("Persons info:\n" + p.toString());
//If you want directly to "output the object" you have to override the toString() method anyway:
//System.out.println(p);//"Outputting the object", this is possible because I have overridden the toString() method
p.showInfo();
}
}

Final print statement returning null (java)

I have a basic name application that is taking in user data from the main class, splits the data in the parser class and then tries to assign everything in the final class and print it out in the toString method. I know the main class and the parser are working fine. I have verified in the parser class that the data DOES split properly and also sends the data through the object I made to the final class to assign it all. However, my final code is returning null..
MAIN CLASS
import java.util.Scanner;
public class MainClass {
public static void main (String[]args)
{
Scanner input = new Scanner(System.in); //create scanner object to gather name information
String fullName = null; //set the predefined value for the users name to null
nameParse splitInformation = new nameParse(); //method build to split the name into different sections
SecondClass access = new SecondClass(); //class built to output the different name data
System.out.println("What is your name?");
fullName = input.nextLine(); //store the users name and pass it into the data parser
splitInformation.parseNameInformation(fullName); //name parsing parameters built
System.out.println(access.toString());
}
}
Data Parser Class
public class nameParse {
private String firstName;
private String middleName;
private String lastName;
public nameParse()
{
firstName = "initial";
middleName = "initial";
lastName = "initial";
}
public void parseNameInformation(String inputInfo)
{
//Create an array to store the data and split it into multiple sectors
String nameInformation[] = inputInfo.split("\\s");
firstName = nameInformation[0];
middleName = nameInformation[1];
lastName = nameInformation[2];
//System.out.println(firstName + " " + middleName + " " + lastName);
SecondClass sendData = new SecondClass();
sendData.setFirstName(firstName);
sendData.setMiddleName(middleName);
sendData.setLastName(lastName);
}
}
Final Class
__
public class SecondClass {
private String firstName;
private String middleName;
private String lastName;
/*public String GFN()
{
return firstName;
}
public String GMN()
{
return middleName;
}
public String GLN()
{
return lastName;
}*/
public String setFirstName(String yourFirstName)
{
firstName = yourFirstName;
return this.firstName;
}
public String setMiddleName(String yourMiddleName)
{
middleName = yourMiddleName;
return this.middleName;
}
public String setLastName(String yourLastName)
{
lastName = yourLastName;
return this.lastName;
}
public String getFN()
{
return firstName;
}
public String toString()
{
String printNameInfo = "\nYour First Name:\t" + getFN();
return printNameInfo;
}
}
You never set any of your SecondClass object's (called "access") fields, so of course they'll all be null.
So in short, your code creates a nameParse object, gets information from the user, but does nothing with that information. You create a SecondClass object called access, put no data into it, and so should expect no valid data in it when you try to print it out. Solution: put information into your SecondClass object first. Call its setter methods:
// be sure to call the setter methods before trying to print anything out:
access.setSomething(something);
access.setSomethingElse(somethingElse);
Edit
You state:
I thought I set the data using the sendData.setFirstname(...) etc?
In the parseNameInformation method you create a new SecondClass object and you do set the fields of this object, but this object is completely distinct from the one in your main method whose fields are still null. To solve this, give parseNameInformation a method parameter and pass in your main method's SecondClass object into it and set its methods. You'll have to create the SecondClass object before calling the method of course.
i.e.,
public void parseNameInformation(String inputInfo, SecondClass sendData)
{
//Create an array to store the data and split it into multiple sectors
String nameInformation[] = inputInfo.split("\\s");
firstName = nameInformation[0];
middleName = nameInformation[1];
lastName = nameInformation[2];
//System.out.println(firstName + " " + middleName + " " + lastName);
// SecondClass sendData = new SecondClass(); // !!! get rid of this
sendData.setFirstName(firstName);
sendData.setMiddleName(middleName);
sendData.setLastName(lastName);
}

Categories

Resources