As a task in my beginners course in object oriented programming, I must set two objects in my Partner class as "married".
This is my attempt at beginning:
public class Partner {
String name;
String partner;
public Partner(String name, String partner) {
super();
this.name = name;
this.partner = partner;
}
public String getPartner() {
return partner;
}
public void setPartner(Partner()) { //think i need the object here?
this.partner = partner; //however i don't know how
}
public String getName() {
return name;
}
public static void main(String[] args) {
Partner p1 = new Partner("Name1", idk);
Partner p2 = new Partner("Name2", idk);
}
}
My issue is that I don't know how to use the object in the setPartner method, if that's even the correct way to do it. It should also be possible to get a divorce from the other object by setting one of the objects' partner to null.
It should also make it so that the partners automatically register as married to eachother if one of them is set a married to the other. For example, if p1 is set as the partner of p2, p2 should automaticly be set as the parter to p1 as well.
Create two constructors: one with just name and another with name and partner (of type, Partner) so that you will have the flexibility to initialize an object with just name and then set its partner or initialize with name and partner (if the partner is known).
public class Partner {
private String name;
private Partner partner;
public Partner(String name) {
this.name = name;
}
public Partner(String name, Partner partner) {
this.name = name;
setPartner(partner);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setPartner(Partner partner) {
partner.partner = this;
this.partner = partner;
}
#Override
public String toString() {
String value;
if (partner != null) {
value = name + ", partner=" + partner.name;
} else {
value = name;
}
return value;
}
public static void main(String[] args) {
// Example 1
Partner p1 = new Partner("Name1");
Partner p2 = new Partner("Name2");
p1.setPartner(p2);
System.out.println(p1);
System.out.println(p2);
// Example 2
Partner p3 = new Partner("Name3");
Partner p4 = new Partner("Name4", p3);
System.out.println(p3);
System.out.println(p4);
}
}
Output:
Name1, partner=Name2
Name2, partner=Name1
Name3, partner=Name4
Name4, partner=Name3
Are you asking how to write setter methods ? Something like this
public void setPartner(String partner) {
this.partner= partner;
}
If you intend for a Partner object to have a pointer to another object of this class, you should change String partner to Partner partner.
You won't always have an initialized Partner object to use in the Partner constructor, so you have 3 options:
add another constructor which doesn't require an argument of type Partner
change the existing constructor
pass null as argument.
In any case, you'll have to initialize the partner field somewhere else.
That's where setters come in. The correct syntax for your setPartner function would be:
public void setPartner(Partner partner) {
this.partner = partner;
}
getPartner() function should be changed accordingly to return the correct type.
Your code in main() can then be something like this:
Partner p1 = new Partner("Name1", null);
Partner p2 = new Partner("Name2", p1);
p1.setPartner(p2);
It should also be possible to get a divorce from the other object by setting one of the objects' partner to null.
That is accomplished by using p.setPartner(null), where p is an object of type Partner. You might also want to set both objects partners to null instead of just one, for easier checking.
Related
String answer = question1?.question2?.answer
Is there a way (preferably in-built) to get the property of an object where both the following scenarios are covered:
If the object is null, return a null value for the attribute.
Returns null for an attribute if it doesn't exist in the object.
To top this, is there a way to chain such get operations for deeply nested attributes?
Java doesn't however Groovy does. When writing Groovy you can mix java right in with it. In Groovy you can do println company?.address?.street?.name
it's possible to obtain "similar" behavior(chain) but just with custom code ( not being something inbuild)
public class TestChain
{
public static void main(String args[])
{
TestChain tc = new TestChain();
Person p = tc. new Person();
p.setName("pName").getMsg().setAge(10).getMsg();
}
class Person
{
String name;
int age;
public Person setName(String name)
{
this.name = name;
return this;
}
public Person setAge(int age)
{
this.age = age;
return this;
}
public Person getMsg()
{
System.out.println(this);
return this;
}
public String toString()
{
return "name="+name+",age="+age;
}
}
}
Output:
name=pName,age=0
name=pName,age=10
Basically methods to be chained need to return current instance.
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
Customer is a class. The Class list is arraylist of Customer.
I have added the Customers to list but when I want to print all the customer names from the list I get null only.
import java.util.*;
public class Assignment1 {
public static void main(String args[])
{
List list = new List();
list.addCustomer("man");
list.addCustomer("man");
//System.out.println(list);
list.printx();
}
}
class Customer{
public String name;
public Customer(String name)
{
name = this.name;
}
}
class List
{
ArrayList<Customer> list = new ArrayList<Customer>();
public void addCustomer(String name1)
{
Customer x = new Customer(name1);
list.add(x);
System.out.println(list.get(0));
}
public void printx()
{
for(int i =0;i < list.size();i++)
{
System.out.println(list.get(i).name);
}
}
}
Inside your Customer constructor, you need to set ::
this.name = name;
and not the other way round! :P
What you have done right now is that you change the function parameter name to the class parameter name which is currently null(default initialization). So, you never initialize name variable of the Customer class, and hence you always get null when you print it.
I suggest you override the toString method in class Customer, it helps you debug your Customer objects. For example, you can change the local variable to assignedName as below:
class Customer{
public String name;
public Customer(String name)
{
this.name = name;
}
#Override
public String toString(){
return "customer name:" + this.name;
}
}
this.name and name are different things in the Customer constructor:
this.name is an instance variable and name is a local variable defined in your constructor.
// you should narrow the modifier to private, and implement getter and setter for it
public String name;
public Customer(String assignedName){
this.name = assignedName;
}
I have following code:
public class Address {
private String city;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
And I have another class User with ArrayList<Address> as member variable as follows.
import java.util.ArrayList;
public class User {
private String name;
private ArrayList<Address> listOfAddresses ;
public ArrayList<Address> getListOfAddresses() {
return listOfAddresses;
}
public void setListOfAddresses(ArrayList<Address> listOfAddresses) {
this.listOfAddresses = listOfAddresses;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And in the class with the main method, I have created user object which has two member variable such as name and listofAddresses. Now, I need some guidance about how to set value for listOfAddresses using user object. And also how to retrieve using user object.
My main class looks like this.
import java.util.ArrayList;
public class ArrayImpl {
public static void main(String[] args) {
User user = new User();
user.setName("First User");
Address address = new Address();
address.setCity("Melbourne");
user.setListOfAddresses(address);
}
}
And I'm getting error at the user.setListofAddressess(address) as:
The method setListOfAddresses(ArrayList) in the type User is
not applicable for the arguments (Address)
My understanding is that listOfAddresses is an ArrayList of type Address and thus I'm trying to use setter method of listOfAddresses member variable to set it's value.
Can somebody please help me how to set listOfAddresses and retrieve using user object.
You have primarily two options:
Ugly Way
You retrieve the current list of addresses by calling the Getter, then adding your new address, then calling the Setter with your new list:
List<Address> addresses = user.getListOfAddresses();
addresses.add(address);
user.setListOfAddresses(addresses);
The smart and cool way
Your class User provides delegates to add and remove Addresses. For this, add methods for your purposes in your User class:
public void addAddress(Address a) {
this.listOfAddresses.add(a);
}
You are trying to set variable of type 'address' in user object but you are supposed to set an object of type ArrayList their.
User user = new User();
ArrayList<Address> ar=new ArrayList<>();
Address ad1=new Address();
ad1.setCity("Melbourne");
ar.add(ad1);
user.setListOfAddresses(ar);
Your method definition for setListOfAddresses in User class takes as argument an object of type ArrayList<Address>, but in your main you're trying to pass it an instance of Address.
This is the right approach:
ArrayList<Address> addrList = user.getListOfAddresses();
if (addrList == null) {
//If it's the first address you insert, you have to initialize the ArrayList
addrList = new ArrayList<Address>();
}
addrList.add(address);
Then to retrieve each address i straightforward:
ArrayList<Address> addrList = user.getListOfAddresses();
for (Address a : addrList) {
//do something with a....
}
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).