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;
}
}
}
Related
package week3;
import java.util.ArrayList;
public abstract class TaxPayer {
private final String TFN;
private String firstName;
private String lastName;
private double income;
private Address address(int streetNumber, String streetName, String suburb,
String city, String state, int postcode);
public TaxPayer(String TFN, String firstName, String lastName, double income,
Address address) {
this.TFN = TFN;
this.firstName = firstName;
this.lastName = lastName;
this.income = income;
this.address = address;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public double getIncome() {
return income;
}
public Address getAddress() {
return address;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setIncome(double income) {
this.income = income;
}
public void setAddress(Address i) {
}
public String getFullName() {
return getFirstName() + " " + getLastName();
}
#Override
public String toString() {
return TFN + " " + firstName + " " + lastName + " "
+ income;
}
public static double calcTax(double income) {
return 1;
}
public double calcTax() {
return 1;
}
public static void printArrayListToConsole(ArrayList<TaxPayer> Array) {
for (TaxPayer d : Array) {
System.out.println(d);
}
}
}
package week3;
public class Address {
int streetNumber;
String streetName;
String suburb;
String city;
String state;
int postcode;
public Address(int streetNumber, String streetName, String suburb,
String city, String state, int postcode) {
this.streetNumber = streetNumber;
this.streetName = streetName;
this.suburb = suburb;
this.city = city;
this.state = state;
this.postcode = postcode;
}
#Override
public String toString() {
return streetNumber + " " + streetName + " " + suburb + " " + city + " "
+ state + " " + postcode;
}
}
So, my problem is in creating the address attribute, which must be private. I think I've made the other class correctly yet it still isn't working. As well as this, the attribute isn't working with the fields I try to put in it (streetNumber, streetName, etc), it's coming up with the error 'missing method body, or declare abstract' but I'm unsure why. Any help is appreciated!
private Address address(int streetNumber, String streetName, String suburb,
String city, String state, int postcode);// this is a method not a attribute
Make private attribute of Address Class.
public abstract class TaxPayer {
.
.
.
private Address address; // this is attribute.
.
.
.
//One way is passing the all address attributes in constructor
public TaxPayer(String TFN, String firstName, String lastName, double income,int streetNumber, String streetName, String suburb,
String city, String state, int postcode) {
this.TFN = TFN;
this.firstName = firstName;
this.lastName = lastName;
this.income = income;
this.address = new Address(streetNumber, streetName, String suburb,city, state, postcode);
}
}
second option is use same constructor and make a Address objectin main class and pass into that constructor like :
public TaxPayer(String TFN, String firstName, String lastName, double income,Address address) {
this.TFN = TFN;
this.firstName = firstName;
this.lastName = lastName;
this.income = income;
this.address = address;
}
And while creating Tax Payer Object first create Address Object and pass it.
Address address= new Address(streetNumber, streetName, String suburb,city, state, postcode);
TaxPayer tp= new TaxPayer(TFN, firstName, lastName, income,address);
private Address address(int streetNumber, String streetName, String suburb,
String city, String state, int postcode);
You have to declaring a variable of Address type but this is not the way to declare a variable.
Replace the above code of TaxPayer class with just this
private Address address;
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).
New to Java!
I have created a class that has constructors for various fields. However, when I try and print the fields, I recieve "null" as the output. Please help me understand why. Here is the class:`
public class User {
//All relevant information to identify each user.
private String FirstName;
private String LastName;
private String Email;
private long PhoneNum;
private long CardNum;
//Build Constructors for User info.
public User(String Fname, String Lname, String Mail, long num, long card)
{
Fname=FirstName;
Lname=LastName;
Mail=Email;
num=PhoneNum;
card=CardNum;
}
//Method to set FirstName.
public void setFirstName (String Fname)
{
FirstName=Fname;
}
//Method to get FirstName.
public String getFirstName()
{
return FirstName;
}
//Method to set LastName.
public void setLastName (String Lname)
{
LastName=Lname;
}
//Method to get Lastname.
public String getLastname()
{
return LastName;
}
//Method to set email.
public void setEmail (String Mail)
{
Email=Mail;
}
//Method to get email.
public String getEmail()
{
return Email;
}
//Method to set phonenumber.
public void setPhoneNum(long num)
{
PhoneNum=num;
}
//Method to get phonenumber.
public long getPhoneNum()
{
return PhoneNum;
}
//Method to set credit card number.
public void setCardNum(long card)
`enter code here`{
CardNum=card;
}
// Method to get credit card number.
public long getCardNum()
{
return CardNum;
}
Now when I run this code, I receive "null":
public class UserDemo {
public static void main(String[] args)
{
String first="Matt";
String last="Burns";
String email="mburns267#yahoo.com";
long phone=333;
long card=222;
User Matt=new User(first,last,email,phone,card);
System.out.print(Matt.getLastname());
}
What am I doing wrong? Thank you in advance!
`
Is the other way around, instead of:
public User(String Fname, String Lname, String Mail, long num, long card){
Fname=FirstName;
Lname=LastName;
Mail=Email;
num=PhoneNum;
card=CardNum;
}
it should be:
public User(String Fname, String Lname, String Mail, long num, long card){
FirstName = Fname;
LastName = Lname;
Email = Mail;
PhoneNum = num;
CardNum = card;
}
To avoid this kind of thing you can use the this keyword. Here is an example:
String firstName;
public Constructor(String firstName){
this.firstName = firstName;
}
You have your constructor assignments the wrong way:
public User(String Fname, String Lname, String Mail, long num, long card)
{
// this refers to the current object being constructed
this.FirstName = Fname;
this.LastName = Lname;
this.Email = Mail;
this.PhoneNum = num;
this.CardNum = card;
}
Java constructor objects should be created like so:
public User(String Fname, String Lname)
{
this.firstName = Fname;
//keyword 'this' refers to the new object, so the new object's Fname would equal the firstName place below
this.lastName = Lname; //same as above
}
To create a new User, use this code:
User Matt = new("Matt", "Burns"); //Creates a new User Matt, with firstName "Matt" and lastName "Burns"
System.out.println(Matt.getfirstName()); //prints User Matt's firstName to the console.
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.
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.