Summary:
New to Java, tried looking through other posts but didn't find an answer. I'm learning inheritance and have an AddressBook class extended by a Runner class. When I write a program to test the inheritance I create a Runner object. If I get the first String parameter it returns fine but when I attempt to get the second String parameter it returns null.
Question:
Why is the second parameter returning null?
package Assignment_1;
//Begin Class Definition
public class AddressBook {
// Member variables
private String businessPhone;
private String cellPhone;
private String facebookId;
private String firstName;
private String homeAddress;
private String homePhone;
private String lastName;
private String middleName;
private String personalWebSite;
private String skypeId;
//Constructors
public AddressBook (String firstName, String middleName, String lastName, String homeAddress, String businessPhone, String homePhone, String cellPhone, String skypeId, String facebookId, String personalWebSite) {
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
this.homeAddress = homeAddress;
this.businessPhone = businessPhone;
this.homePhone = homePhone;
this.cellPhone = cellPhone;
this.skypeId = skypeId;
this.facebookId = facebookId;
this.personalWebSite = personalWebSite;
}
public AddressBook (String firstName) {
this.firstName = firstName;
}
public AddressBook(String firstName, String middleName) {
this.firstName = firstName;
this.middleName = middleName;
}
public AddressBook (String firstName, String middleName, String lastName) {
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
}
// Getters and setters
public String getFirstName() {
return firstName;
}
public String getMiddleName() {
return middleName;
}
public String getLastName() {
return lastName;
}
public String getHomeAddress() {
return homeAddress;
}
public String getBusinessPhone() {
return businessPhone;
}
public String getHomePhone() {
return homePhone;
}
public String getCellPhone() {
return cellPhone;
}
public String getSkypeId() {
return skypeId;
}
public String getFacebookId() {
return facebookId;
}
public String getPersonalWebsite() {
return personalWebSite;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setHomeAddress(String homeAddress) {
this.homeAddress = homeAddress;
}
public void setBusinessPhone(String businessPhone) {
this.businessPhone = businessPhone;
}
public void setHomePhone(String homePhone) {
this.homePhone = homePhone;
}
public void setCellPhone(String cellPhone) {
this.cellPhone = cellPhone;
}
public void setSkypeId(String skypeId) {
this.skypeId = skypeId;
}
public void setFacebookId(String facebookId) {
this.facebookId = facebookId;
}
public void setPersonalWebSite(String personalWebSite) {
this.personalWebSite = personalWebSite;
}
// Public methods
public static void compareNames(String name1, String name2) {
if(name1.equals(name2)) {
System.out.println(name1);
System.out.println(name2);
System.out.println("The names are the same.");
} else {
System.out.println(name1);
System.out.println(name2);
System.out.println("The names appear to be different.");
}
}
************************************************************
package Assignment_1;
public class BanffMarathonRunner extends AddressBook {
// Member variables
private int time;
private int years;
// Constructors
public BanffMarathonRunner(String firstName, String lastName, int min, int yr) {
super(firstName, lastName);
time = min;
years = yr;
}
// Getters and Setters
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
public int getYears() {
return years;
}
public void setYears(int years) {
this.years = years;
}
}
************************************************************
package Assignment_1;
import Assignment_1.BanffMarathonRunner;
public class TestBanffMarathonRunner {
public static void main(String[] args) {
BanffMarathonRunner r1 = new BanffMarathonRunner("Elena", "Brandon", 341, 1);
System.out.print(r1.getLastName());
}
}
}
Because lastName is null.
You are calling AddressBook(String firstName, String middleName)
and setting the middleName, not the lastName.
BanffMarathonRunner r1 = new BanffMarathonRunner("Elena", "Brandon", 341, 1);
calls:
// firstName = "Elena"
// lastName = "Brandon"
// min = 341
// yr = 1
public BanffMarathonRunner(String firstName, String lastName, int min, int yr) {
super(firstName, lastName);
// ...
}
which calls via super(...):
// firstName = "Elena"
// middleName = "Brandon" <-- here is your issue
public AddressBook(String firstName, String middleName) {
this.firstName = firstName;
this.middleName = middleName;
}
Brandon is set in AddressBook#middleName instead of AddressBook#lastName.
Your problem is in the BanffMarathonRunner.java:
in the constructor when you are calling the
super(firstName, lastName);
Actually by the call above the super class constructor with two parameter is being called, and that constructor is the one which set the middleName not the lastName.
I think you are confused because of the lastName variable name, which is passed to the constructor with two argument and that constructor use the second argument to set the middleName.
Good Luck.
Related
I want to create a POJO class with Constructor for the POST request body which has nested JSON, But I am not sure how to call JSONArray inside it?
PS: I do not want to set data using the setter method, I want to use Constructor for setting the data.
Here is the JSON:
{
"FirstName": "test",
"LastName": "account",
"PASSWORD": "Password123*",
"Email": [
{
"TYPE": "Primary",
"VALUE": "arpitay6#mail7.io"
}
]}
POJO I've created -
import java.util.List;
public class PostAccountCreateAPI {
private List <Email> email;
private String password;
private String firstname;
private String lastname;
public PostAccountCreateAPI(List<Email> email, String password, String firstname, String lastname) {
this.email = email;
this.password = password;
this.firstname = firstname;
this.lastname = lastname;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<Email> getEmail() {
return email;
}
public void setEmail(List<Email> email) {
this.email = email;
}
}
package pojo;
public class Email {
private String type;
private String value;
public Email(String type, String value) {
this.type = type;
this.value = value;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
In the main method, I am calling POJO using -
PostAccountCreateAPI PostAccountCreateAPIPayLoad = new PostAccountCreateAPI("pri#mail7.io", "P#$$w0rd", "arpita", "garg");
But It is not working. Can anyone please suggest how to do this?
Ok....Here I am Giving a complete example:
The PostAccountCreateApi class:
import java.util.List;
public class PostAccountCreateAPI{
private String FirstName;
private String LastName;
private String PASSWORD;
private List<Email> Email;
public PostAccountCreateAPI(){}
public PostAccountCreateAPI(String FirstName, String LastName, String PASSWORD, List<Email> Email){
this.FirstName = FirstName;
this.LastName = LastName;
this.PASSWORD = PASSWORD;
this.Email = Email;
}
public void setFirstName(String FirstName){
this.FirstName = FirstName;
}
public String getFirstName(){
return this.FirstName;
}
public void setLastName(String LastName){
this.LastName = LastName;
}
public String getLastName(){
return this.LastName;
}
public void setPASSWORD(String PASSWORD){
this.PASSWORD = PASSWORD;
}
public String getPASSWORD(){
return this.PASSWORD;
}
public void setEmail(List<Email> Email){
this.Email = Email;
}
public List<Email> getEmail(){
return this.Email;
}
}
The Email Class:
public class Email {
String TYPE;
String VALUE;
public Email() {
}
public Email(String TYPE, String VALUE) {
this.TYPE = TYPE;
this.VALUE = VALUE;
}
public void setTYPE(String TYPE) {
this.TYPE = TYPE;
}
public String getTYPE() {
return this.TYPE;
}
public void setVALUE(String VALUE) {
this.VALUE = VALUE;
}
public String getVALUE() {
return this.VALUE;
}
}
The main class with a dummy main method:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Email> emailList = new ArrayList<>();
emailList.add(new Email("Primary", "pri#mail7.io"));
emailList.add(new Email("Primary", "amimulahsan7#gmail.com"));
//And list goes on......
PostAccountCreateAPI postAccountCreateAPI = new PostAccountCreateAPI("arpita", "garg",
"P#$$w0rd", emailList);
}
}
The first parameter to the constructor is List<Email>, but you are currently passing a String as the first argument to the constructor. Create a list of Email objects and then invoke the PostAccountCreateAPI constructor.
I need help creating a method to find an object in an array and making a loop to change the object.
public void changeABFF() {
System.out.println("Enter first and the last name of the best friend you would like to change: ");
String fname = keyboard.next();
String lname = keyboard.next();
BestFriends other = new BestFriends(fname,lname,"","");
boolean found = false;
for(int i=0;i<myBFFArray.length && found == false;i++) {
if(other.equals(myBFFs.get(i))) {
found = true;
System.out.println("Enter a First Name: ");
String fName = keyboard.next();
System.out.println("Enter a Last Name: ");
String lName = keyboard.next();
System.out.println("Enter a Nick Name: ");
String nName = keyboard.next();
System.out.println("Enter a phone number");
String cPhone = keyboard.next();
BestFriends tmp = myBFFs.get(i);
tmp.firstName = fName;
tmp.setLastname(lName);
tmp.setNickName(nName);
tmp.setCellPhone(cPhone);
}
}
}
So I'm changing from array list to array and changed the name to myBFFArray
My question, is how do I create a find method to match up user input to value in the array?
You can edit your BestFriends class to override equals and hashCode to compare two BestFriends objects
public class BestFriends {
private String firstName;
private String lastName;
private String nickName;
private String cellPhone;
public BestFriends(String firstName, String lastName, String nickName, String cellPhone) {
this.firstName = firstName;
this.lastName = lastName;
this.nickName = nickName;
this.cellPhone = cellPhone;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getCellPhone() {
return cellPhone;
}
public void setCellPhone(String cellPhone) {
this.cellPhone = cellPhone;
}
#Override
public int hashCode() {
return this.hashCode();
}
#Override
public boolean equals(Object obj) {
BestFriends bf = (BestFriends) obj;
return bf.getFirstName().equals(firstName) && bf.getLastName().equals(lastName) && bf.getNickName().equals(nickName) && bf.getCellPhone().equals(cellPhone);
}
After that when you iterate over the array
public BestFriends find(String firstName, String lastName, String nickName, String cellPhone) {
BestFriends bestFriends = new BestFriends(firstName, lastName, nickName, cellPhone);
for (BestFriends b: myBFFArray) {
if (b.equals(bestFriends)) {
return b;
}
}
}
I have two string
private StringProperties firstName;
private StringProperties lastName;
private StringProperties nickName;
the first and last name are picked by user, the nickName is a concatenation of first 3 character of first and lastname
How i can do that?
Actually i initialize it like that (this is the entire class).
public class Person {
private StringProperty firstName;
private StringProperty lastName;
private StringProperty nickName;
private ObservableList<Evento> eventi = FXCollections.observableArrayList();
public Person(String firstName, String lastName) {
this.firstName = new SimpleStringProperty(firstName);
this.lastName = new SimpleStringProperty(lastName);
if (firstName.length() > 2 && lastName.length() > 2)
this.nickName = new SimpleStringProperty(firstName.trim().substring(0,3).concat(lastName.trim().substring(0,3)));
else
this.nickName = new SimpleStringProperty("");
}
public ObservableList<Evento> getEventi() {
return eventi;
}
public String getFirstName() {
if(firstName == null) firstName = new SimpleStringProperty(this,"firstName");
return firstName.get();
}
public StringProperty firstNameProperty() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName.set(firstName);
}
public String getLastName() {
if(lastName == null) lastName = new SimpleStringProperty(this, "lastName");
return lastName.get();
}
public StringProperty lastNameProperty() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName.set(lastName);
}
public String getNickName() {
if(nickName == null) nickName = new SimpleStringProperty(this,"nickName");
return nickName.get();
}
public StringProperty nickNameProperty() {
return nickName;
}
#Override
public String toString() {
return getNickName() + "(" + getLastName() + " " + getFirstName() + ")";
}
}
but when i let the user change first or lastName, the nickName won't update.
You should use ReadOnlyStringProperty for the nickname:
private ReadOnlyStringWrapper nickName= new ReadOnlyStringWrapper();
...
public final String getNickName() {
return nickName.get();
}
public final ReadOnlyStringProperty nickNameProperty() {
return nickName.getReadOnlyProperty();
}
As for binding, you can use utility methods from Bindings class or implement your own binding for any other complicated cases. This example uses createStringBinding() method. It takes Callable functional interface, which will be used to calculate new value, and list of observable properties, which values will be observed for changes:
public Person(String firstName, String lastName) {
this.firstName = new SimpleStringProperty(firstName);
this.lastName = new SimpleStringProperty(lastName);
this.nickName.bind(Bindings.createStringBinding(()->{
if(this.firstName.get().length() > 2 && this.lastName.get().length() > 2) {
return this.firstName.get().substring(0,3).concat(this.lastName.get().trim().substring(0,3));
} else {
return "";
}
}, this.firstName, this.lastName));
}
You can use Bindings.format:
nickName.bind(Bindings.format("%.3s%.3s", firstName, lastName));
The 3 in %.3s is the maximum length of the string.
This won't do any trimming of the strings though, (you could do that before passing the strings to firstName and lastName).
It will also work on strings that are smaller than 3 characters. So, you can get nicknames like FoBar, FooB or Bar (if the first name is an empty string).
Please help me find errors from this code. I'm still new and I don't know if this is correct or not.
I do have one error.
This is the error:
constructor Person in class Person cannot be applied to given types;
super();
^
required: String,String,String
found: no arguments
reason: actual and formal argument lists differ in length
This is my code:
import java.util.*;
public class Person {
//Data fields
private String lastName;
private String middleInitial;
private String firstName;
//Constructors
public Person(String lastName, String middleInitial, String firstName) {
this.lastName = lastName;
this.middleInitial = middleInitial;
this.lastName = lastName;
}
//Accessor methods
public String getlastName() {
return lastName;
}
public String getmiddleInitial() {
return middleInitial;
}
public String getfirstName() {
return firstName;
}
//Mutator methods
public void setlastName(String lastName) {
lastName = lastName;
}
public void setmiddleInitial(String middleInitial) {
middleInitial = middleInitial;
}
public void setfirstName(String firstName) {
firstName = firstName;
}
public String getName() {
String studentName = this.lastName + ", " + this.firstName +
this.middleInitial + ".";
return studentName;
}
} //end Person class
class Address {
//Data fields
private String streetName;
private int zipCode;
private String state;
private String country;
//Constructors
public Address(String streetName, int zipCode, String state,
String country) {
this.streetName = streetName;
this.zipCode = zipCode;
this.state = state;
this.country = country;
}
//Accessor methods
public String getstreetName() {
return streetName;
}
public int getzipCode() {
return zipCode;
}
public String getstate() {
return state;
}
public String getcountry() {
return country;
}
//Mutator methods
public void setstreetName(String streetName) {
streetName = streetName;
}
public void setzipCode(int zipCode) {
zipCode = zipCode;
//Integer.toString(zipCode);
}
public void setstate(String state) {
state = state;
}
public void setcountry(String country) {
country = country;
}
public String getAddress() {
String studentAddress = streetName + "\n" + state + ", " + country +
"\n" + zipCode;
return studentAddress;
}
} //end Address class
class Student extends Person {
private String dateOfBirth;
//Constructors
public Student (String studentName, String dateOfBirth) {
super();
dateOfBirth = dateOfBirth;
}
//Accessor methods
public String getdateOfBirth() {
return dateOfBirth;
}
//Mutator methods
public void setdateOfBirth() {
this.dateOfBirth = dateOfBirth;
}
public String toString() {
return ("Date of Birth: " + dateOfBirth);
}
} //end Student subclass
Edited: If I do so for both the Person and Address class. I can only have three-arg constructors. How can I call a one-arg constructor?
For example, I have
public Student (String firstName, String lastName, String middleInitial, String dateOfBirth) {
super(firstName, lastName, middleInitial); and
public Student (String streetName, String state, String country) {
super(streetName, state, country);
How can I get zipcode separately?
Class Person has a constructor, therefore the default no-arg constructor is not created for you. Therefore you can't call super() in Student's constructor, you have to call super(lastName, middleInitial, firstName);.
Or you could create a new Person no-arg constuctor.
Try this
In student class
public Student ( String lastName, String middleInitial, String firstName,String studentName, String dateOfBirth) {
super( lastName, middleInitial,firstName);
this.dateOfBirth = dateOfBirth;
}
Or
In Person class create no arg consructor. Eg:
public Person(){}
Person Class has a constructor with arguments. So default constructor will not be created. So you have to pass 3 String parameters in super(3 String parameters) or you have to create a constructor which does not take any parameter in person class.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
This is my class for Address Book Entry
public class AddressBookEntry {
private String firstname;
private String lastname;
private int streetno;
private String street;
private String city;
private int telephonenumber;
private String emailaddress;
public AddressBookEntry(String firstname, String lastname, int streetno,
String street, String city, int telephonenumber, String emailaddress) {
super();
this.firstname = firstname;
this.lastname = lastname;
this.streetno = streetno;
this.street = street;
this.city = city;
this.telephonenumber = telephonenumber;
this.emailaddress = emailaddress;
}
public AddressBookEntry() {
// TODO Auto-generated constructor stub
}
THESE ARE THE SETTER-GETTER
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public int getStreetno() {
return streetno;
}
public void setStreetno(int streetno) {
this.streetno = streetno;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public int getTelephonenumber() {
return telephonenumber;
}
public void setTelephonenumber(int telephonenumber) {
this.telephonenumber = telephonenumber;
}
public String getEmailaddress() {
return emailaddress;
}
public void setEmailaddress(String emailaddress) {
this.emailaddress = emailaddress;
}
THIS IS THE CUSTOM METHODS
public String fullName() {
return this.firstname + " " + this.lastname;
}
public String fullAddress() {
return this.streetno + " " + this.street + " st. " + this.city + " city";
}
public void displayAddress(){
System.out.println("Name : " + fullName());
System.out.println("Address : " + fullAddress());
System.out.println("Telephone Number : " + this.telephonenumber);
System.out.println("Email Address : " + this.emailaddress + "#gmail.com"+"\n");
}
}
NOW THIS IS THE CLASS FOR THE ADDRESSBOOK
import java.util.ArrayList;
import java.util.List;
public class AddressBook {
private List<AddressBookEntry> listOfEntries;
public AddressBook() {
this.listOfEntries = new ArrayList<>();
}
public void add(AddressBookEntry addressBookEntry) {
this.listOfEntries.add(addressBookEntry);
}
public void delete(int index) {
this.listOfEntries.remove(index);
}
public AddressBookEntry get(int index) {
return this.listOfEntries.get(index);
}
public AddressBookEntry[] viewAll() {
AddressBookEntry[] result = new AddressBookEntry[this.listOfEntries.size()];
this.listOfEntries.toArray(result);
return result;
}
}
How can I create a class address book that has a limit of 100 entries of AddressBookEntry objects using the given code above using arrays? While it includes a menu: AddEntry, DeleteEntry, ViewAllEntries, and UpdateEntry?
If you want fixed-sized you should use an array instead of List.
If for some reason you cannot change the list, you can provide the size to the ArrayList constructor.
public AddressBook() {
this.listOfEntries = new ArrayList<>(100);
}
However, you need to check the size before inserting the element.
public void add(AddressBookEntry addressBookEntry) {
if(this.listOfEntries.size() <= 100)
this.listOfEntries.add(addressBookEntry);
else
throw new IllegalStateException("Address book is full");
}