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).
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Beginner here.
I cant get my head around why this code outputs the default halfway through. Can anyone take look?
sorry if the format is wrong, first time posting and will fix if not correct.
public class officemanager {
public static void main(String[] args) {
Staffmember aStaffMember = new Staffmember("Steven", "bob");
System.out.println(aStaffMember.toString());
Programmer appleprg = new Programmer("Marion", "bob", "Java");
appleprg.getLanguage();
System.out.println(appleprg.toString());
Doctor dr = new Doctor();
dr.setWard(5);
dr.setFirstName("ed");
dr.setLastName("fall");
System.out.println(dr.toString());
}
}
OUTPUT
Staffmember firstName=Steven, lastName=bob
Programmer firstName=Marion , lastName=bob language Java
default constructor
Doctor firstName=ed , lastName=fall Ward 5
Sorry guys here the class the default constructor is in. It is the Superclass called Staffmember and the firstname, lastname Strings are passed through it.
package oopinheritance;
public class Staffmember {
private String firstName;
private String lastName;
// default constructor
public Staffmember() {
System.out.println("default constructor");
}
// constructor
public Staffmember(String firstName, String lastName) {
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 toString() {
return "Staffmember firstName="
+firstName+ ", lastName=" + lastName;
}
}
Here is the Doctor class, it is a subclass of Staffmember and it has its own tostring method:
package oopinheritance;
public class Doctor extends Staffmember{
private int ward;
public int getWard() {
return ward;
}
public void setWard(int ward) {
this.ward = ward;
}
public String toString() {
return "Doctor firstName="
+this.getFirstName() + " , lastName=" + this.getLastName() + " \t
ward" + this.ward;
}
}
As you have not shown your whole program, so its hard to tell where is the error, but it might be in the default constructor of the doctor class.
Anyways here is the code that you can refer. It will give the correct output.
Here is the link you can refer to see the execution order
http://javabeginnerstutorial.com/learn-by-example-3/order-of-execution-of-blocks-in-java/
Java Constructors - Order of execution in an inheritance hierarchy
class GfG {
public static void main(String[] args) {
Staffmember aStaffMember = new Staffmember("Steven", "bob");
System.out.println(aStaffMember.toString());
Programmer appleprg = new Programmer("Marion", "bob", "Java");
appleprg.getLanguage();
System.out.println(appleprg.toString());
Doctor dr = new Doctor();
dr.setWard(5);
dr.setFirstName("ed");
dr.setLastName("fall");
System.out.println(dr.toString());
}
}
class Staffmember {
String firstName;
String lastname;
public Staffmember(String firstName, String lastname) {
super();
this.firstName = firstName;
this.lastname = lastname;
}
#Override
public String toString() {
return "Staff Member firstName=" + firstName + ", lastname=" + lastname;
}
}
class Programmer {
String firstName;
String lastName;
String Language;
public String getLanguage() {
return Language;
}
public void setLanguage(String language) {
Language = language;
}
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 Programmer(String firstName, String lastname, String Language) {
super();
this.firstName = firstName;
this.lastName = lastname;
this.Language = Language;
}
#Override
public String toString() {
return "Programmer firstName=" + firstName + ", lastName=" + lastName + ", Language=" + Language;
}
}
class Doctor {
int ward;
String firstName;
String lastName;
public void setWard(int ward) {
this.ward = ward;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastname) {
this.lastName = lastname;
}
public Doctor(int ward, String firstName, String lastName) {
super();
this.ward = ward;
this.firstName = firstName;
this.lastName = lastName;
}
#Override
public String toString() {
return "Doctor ward=" + ward + ", firstName=" + firstName + ", lastName=" + lastName;
}
}
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;
}
}
}
Okay so I'm trying to make more than one constructor with the same name. I'm getting an error and I am not sure why.I'm basically trying to make it so that when a player inputs their name, it will still work even if they don't input a specific field such as a suffix, etc. I'm aware I still have to add the setters and getters later and all that but I'm just trying to get the constructors set up right now. Any idea as to why it is giving me an error?
public class Name {
private String firstName;
private String middleInitial;
private String lastName;
private String suffix;
public String playerName(String firstName, String middleInitial, String lastName, String suffix){
this.firstName = firstName;
this.middleInitial = middleInitial;
this.lastName = lastName;
this.suffix = suffix;
return suffix + firstName + middleInitial + lastName;
}
public String playerName(String firstName, String lastName){
this.firstName = firstName;
this.middleInitial = middleInitial;
this.lastName = lastName;
this.suffix = suffix;
return suffix + firstName + middleInitial + lastName;
}
public String playerName(String firstName, String middleInitial, String lastName){ //this is where the error is. "Duplicate method playerName (String String String) in type Name"
this.firstName = firstName;
this.middleInitial = middleInitial;
this.lastName = lastName;
this.suffix = suffix;
return suffix + firstName + middleInitial + lastName;
}
public String playerName(String firstName, String lastName, String suffix){//same error here
this.firstName = firstName;
this.middleInitial = middleInitial;
this.lastName = lastName;
this.suffix = suffix;
return suffix + firstName + middleInitial + lastName;
}
If you were to call
obj.playerName ("string1", "string2", "string3");
how would java know whether this was
public String playerName(String firstName, String middleInitial, String lastName)
or
public String playerName(String firstName, String lastName, String suffix)
Lets take the constructor where you have the error
public String playerName(String firstName, String middleInitial, String lastName) { /* error */ }
Now this is another one where you have the same error
public String playerName(String firstName, String lastName, String suffix){ /* same error */ }
That is because your are using same DATA TYPE for the arguments in both of them and same number of arguments. So here java won't be able to decide which one to call when you use one of these.
I hope this is clear for you now...
When overloading methods (or constructors), you can only have methods that differ in their type signatures. Thus, only one method (of the same name) that takes three String parameters. However, you currently have no constructors. What I think you really wanted was to create Name instances, perhaps to also have getters and setters and finally to override toString (so you can get the Name as a String). Something like,
public class Name {
private String firstName;
private String middleInitial = "";
private String lastName;
private String suffix = "";
public Name(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public Name(String firstName, String middleInitial, String lastName) {
this(firstName, lastName);
this.middleInitial = middleInitial;
}
public Name(String firstName, String middleInitial, String lastName,
String suffix) {
this(firstName, lastName, middleInitial);
this.suffix = suffix;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleInitial() {
return middleInitial;
}
public void setMiddleInitial(String middleInitial) {
this.middleInitial = middleInitial;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getSuffix() {
return suffix;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(firstName);
if (sb.length() > 0) {
sb.append(' ');
}
if (middleInitial.length() > 0) {
sb.append(middleInitial).append(' ');
}
sb.append(lastName);
if (suffix.length() > 0) {
sb.append(' ');
sb.append(suffix);
}
return sb.toString();
}
}
The example toString is performing String concatenation, and you could do the less efficient
#Override
public String toString() {
String str = firstName;
if (str.length() > 0) {
str += " "; // <-- str = str + " ";
}
if (middleInitial.length() > 0) {
str += middleInitial + " ";
}
str += lastName;
if (suffix.length() > 0) {
str += " " + suffix;
}
return str;
}
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.
New to Java...
I have a name class that has:
private String firstName;
private String middleInitial;
private String lastName;
as its instance variables.
If I had certain data that had only firstName and lastName, no middleInitial, how would I make the constructor so that it took only 2 parameters instead of three?
You simply write a constructor with two parameters and a constructor with three
public YourClass(String firstName, String lastName) {
...
}
public YourClass(String firstName, String middleInitial, String lastName) {
...
}
Callers can then choose to use the appropriate constructor based on their needs.
Well, two options:
Just have a constructor with three parameters, and call it using null or the empty string for middleInitial
Overload the constructors, possibly calling one from the other.
As an example for the latter, using an empty string as the default middle initial:
public Person(String firstName, String middleInitial, String lastName)
{
this.firstName = firstName;
this.middleInitial = middleInitial;
this.lastName = lastName;
}
public Person(String firstName, String lastName)
{
this(firstName, "", lastName);
}
However, the compiler will need to know which one you're calling from the call site. So you can do:
new Person("Jon", "L", "Skeet");
or
new Person("Jon", "Skeet");
... but you can't do:
// Invalid
new Person(firstName, gotMiddleInitial ? middleInitial : ???, lastName);
and expect the compiler to decide to use the "two name" variant instead.
In Java, constructors can't have default arguments. Your only option here is to write two constructors. Fortunately, Java does allow you to call constructors from other constructors. You could do something like:
public class MyClass {
private String firstName;
private String middleInitial;
private String lastName;
public MyClass(String firstName, String middleInitial, String lastName) {
this.firstName = firstName;
this.middleInitial = middleInitial;
this.lastName = lastName;
}
public MyClass(String firstName, String lastName) {
this(firstName, "", lastName);
}
...
}
public Class Name{
private String first;
private String middle;
private String last;
public Name(String first, String middle, String last){
this.first = first;
this.middle = middle;
this.last = last;
}
public Name(String first, String last){
this.first = first;
this.last = last;
}
}
You could use two constructors:
public Person(String firstName, String lastName)
{
this(firstName, null, lastName);
}
public Person(String firstName, String middleInitial, String lastName)
{
this.firstName = firstName;
this.middleInitial = middleInitial;
this.lastName = = lastName;
}
Define 2 constructors, one with 2 parameters and one with 3 parameters.
You can write two constructors.
public Person( String firstName, String lastName, String middleName ) { ... }
public Person( String firstName, String lastName ) { ... }
public void myBike(String name, String color)
{
System.out.println("My bike's name is " + name + " and is " + color + ".");
}
public void myBike(String name, String color, float height)
{
System.out.println("My bike's name is " + name + " and is " + color + ".");
System.out.println("My bike is also " + height + " inches tall.");
}
Builder pattern...
class Name {
Builder builder;
public String getSurname() {
return builder.surname;
}
// getter...
public Name(Builder builder) {
this.builder = builder;
}
class Builder {
String surname = "";
String middleName = "";
String name = "";
Builder surname(String surname) {
this.surname = surname;
return this;
}
Builder middleName(String middleName) {
this.middleName = middleName;
return this;
}
Builder name(String name) {
this.name = name;
return this;
}
Name build() {
return new Name(this);
}
}
}