java - return object value - java

Hi i have the following code:
public List<Person> findAll() {
List<Person> copy = new ArrayList<Person>();
for (Person person : personer) {
copy.add(person);
}
return copy;
}
But when i test this i only retrieve the following and not the value:
[Person#15c7850, Person#1ded0fd,
Person#16a9d42]
How do i get the values and not like above. Where i am inserting the person the code looks like this:
public boolean insert(String name, String nbr) {
if (containsName(name)) {
return false;
}
Person person = new Person(name, nbr);
personer.add(person);
return true;
}
and here is my Person class:
class Person {
private String name;
private String nbr;
public Person (String name, String nbr) {
this.name = name;
this.nbr = nbr;
}
public String getName() {
return name;
}
public String getNumber() {
return nbr;
}
}

You're already receiving the objects you want.
What you see is an internal representation of these objects.
You must iterate through them and call their respective methods to see the information you probably want to see.
If you're not satisfied with these results, you must override toString to provide you with more meaningful information.
Update:
after seeing your edit, you should add toString similar to this one in your Person class:
#Override
public String toString() {
return "Name: " + name + ", number: " + nbr;
}
By the way, you're storing nbr as a string, and it's obvious it should be an integer. So, I'd suggest changing its type to an int or Integer.

You are getting a List object back. You can use the Person object to get the data that you need. To get to the Person objects, iterate over the list.
List<Person> people = findAll();
for Person p : people {
String phoneNumber = p.phoneNumber();
String name = p.Name();
}

Override the toString() method in the Person class if you want a better description when printing the results.

Put something like this in the class Person (don't change the method name!):
public String toString() {
return name;//change this line
}

You are printing out an Object that has the default toString inherited from the Object class. This will print out the type of object it is and its location in memory (ie: Person#1ded0fd).
If you'd like it to see something else, you can override the toString method within your class:
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public String toString() {
return this.name;
}
}
If your class looked like the above, this would allow you to do something like this:
Person p = new Person("John");
System.out.println(p);
> John
You can also just grab it as is and print out any information you want from it without overriding the toString method.
Person p = new Person("John");
System.out.println(p.getName());
> John

What value or class Person's property you aspect to retrieve from the ArrayList? This kind of value(Person#15c7850, etc) shows that the Person's object random id that assigned by JVM when you use
System.out.print(copy).

Related

Trouble using HashMap containing Objects

Please pardon my bad English
I am trying to create a HashMap with a String as a key, and an Object as parameter, which I want to initialise each time the program runs so that its added to a new key in the HashMap.
The problem is, that not all values are returned, and namely the second, gives back a weird output.
package javaex1;
import java.util.*;
public class Javaex1 {
public static void main(String[] args) {
Person obj = new Person("Eminem", "Male");
HashMap<String, Person> MapPerson = new HashMap<String, Person>();
MapPerson.put("Eminem", obj);
System.out.println(MapPerson);
}
}
The object
package javaex1;
public class Person {
String Name;
String Gender;
public Person (String name, String Gend) {
this.Name = name;
this.Gender = Gend;
}
public String getName() {
return Name;
}
public String getGender() {
return Gender;
}
}
Any help or hint is greatly appreciated! Thank you in advance for your time!
The expected results should be "Eminem Male". Instead what I get is this:
{Eminem=javaex1.Person#2a139a55}
This happens because you are trying to print an Object, An Object when printed gives the default toString implementaion of Object class , which is shown below
// implementation of toString in Object class
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
This is what you can see in your current output .
You should ovverride toString method in Person class like this.
public String toString() {
return this.Name + " " + this.Gender;
}
So that it returns the name and gender
You should override toString method in Person class. Like that:
#Override
public String toString() {
return this.Name + " " + this.Gender;
}
You're printing the MapPerson object, not the Person one.
Your code should be:
Person person = MapPerson.get("Eminem");
System.out.println(person.getName() + " " + person.getGender());

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.

How can I print from this object? Java

I need to print the first name, last name, and salary from two employee objects but I keep getting a cannot find symbol error. What would I do to fix this?
Here is the constructor class:
public class Employee
{
private String firstName;
private String lastName;
private double monthlySalary;
public Employee( String firstName1, String lastName1, double monthlySalary1) {
setfirstName(firstName1);
setlastName(lastName1);
setmonthlySalary(monthlySalary1);
}
String getfirstName() {
return firstName;
}
String getlastName() {
return lastName;
}
double getmonthlySalary() {
return monthlySalary;
}
public void setfirstName (String firstName1) {
firstName = firstName1;
}
public void setlastName (String lastName1) {
lastName = lastName1;
}
public void setmonthlySalary (double monthlySalary1) {
monthlySalary = ( monthlySalary1 >= 0 ? monthlySalary1 : 0);
}
}
And here is what I have so far to print the objects:
public class EmployeeTest {
public static void main(String[] args) {
Employee a = new Employee("John", "Smith", 10000);
Employee b = new Employee("Jane", "Smith", 11000);
System.out.print(a.firstName1);
}
}
I need to be able to have it print out something along the lines of "Name: Salary:" But I am clueless as to how to make this work. Any help would be greatly appreciated.
In your employee class, you need to override the toString() method.
You can try something like:
#Override
public String toString()
{
System.out.println("Name: "+name+"Salary: "+salary);
}
Then for each of your employees, when you want to print them, just call
System.out.println(employee);
You cant print out firstName (or firstName1, because that doesnt exist in your class), because its marked as private. You should do something like this:
System.out.print(a.getfirstName())
firstName is private, which means that it cannot be seen outside of the object/class it resides in. I suggest you try overriding the toString() method on your Employee class. That method would have access to all the private members of Employee.
Alternately, you could use getfirstName() to return the first name.
Also, this may be a typo, but there is no firstName1 in Employee - it is firstName.

Return a string and int

How do i return a string and an integer? say i wanted to return
students name which is an string and their mark which is an integer.
I cant do mark=mark+element+(element2+name); that creates an incompatible type.
My suggestion in this type of situation is to create a new class that holds this information. Name it for example StudentMark.
class StudentMark {
private final String name;
private final int mark;
public StudentMark(String name, int mark) {
this.name = name;
this.mark = mark;
}
public String getName() { return name; }
public int getMark() { return mark; }
}
Then in your method that has both the name and mark where you want to return, just do like so.
return new StudentMark("Samuel", 3.2);
Here you can also add any other interesting methods that you might need.
Create a class Student and return a student
class Student{
private String name;
private int mark;
//assessor+ contructors
}
you'll need to define a class for it. the class should have two attributes: a string and an int
Define a class that contains both values and return an object of that class.
create A class with priavte variables for name and marks. and override toString() method.
public class Student{
private int marks;
private String name;
//provde setters and getters for marks and name
public String toString(){
return getName()+getMarks();
}
}
In your Student class, you can have a method:
public String printNameAndGrade() {
return "Name: " + this.getName() + "\n " + "Grade: " + this.getGrade();
}
and then call it with a Student object reference:
Student st1 = new Student("Gabe Logan", 97);
System.out.println(st1.printNameAndGrade()); //use `println` method to display it.
You can use a two element Array or List and put the values in there. Unfortunately this looses all type Information.
You can use a Map which keeps the type information, but might be confusing because you would expect an arbitrary number of entries.
The cleanest option is to create a simple class with the two elements.

Categories

Resources