I am trying to change a String in an Arraylist but having some trouble being able to access the correct position to change.
So I am tried using students.get(i).getFirstName() = newFirstName; but I was just really just trying different things at this point.
Below is the code I am trying to make changes for firstName and lastName. This is my editStudentId method
public void editStudentID(int findStudentId) {
for (int i = 0; i < students.size(); i++) {
if (students.get(i).getId() != findStudentId) {
continue;
}
System.out.println("Found a profile containing information for " + findStudentId + ":");
System.out.println("What would you like to change in your profile?");
System.out.println("1.First Name");
System.out.println("2.Last Name");
int decision = scanner.nextInt();
switch (decision) {
case 1:
System.out.println("Enter a new first name to continue");
String newFirstName = scanner.next();
//so this is the part when I am currently working on but am having some trouble doing so
students.get(i).getFirstName() = newFirstName;
break;
case 2:
System.out.println("Enter a new last name to continue");
break;
}
return;
}
System.out.println(" Id not found ");
}
Here is my class for Students
public class Student {
private final int id;
private final String firstName;
private final String lastName;
private final String dob;
public Student(int id,String firstName, String lastName, String dob) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.dob = dob;
}
public int getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getDob() {
return dob;
}
public static Student createStudentID(int id,String firstName, String lastName, String dob)
{
return new Student(id,firstName, lastName, dob);
}
}
You should add a set function:
public void setFirstName(String newFirstName) {
firstName = newFirstName;
}
Same for the other variables. Setters and Getters are your friends.
Then call these functions. Use get* to use the variable, not change. Use set to change the variable.
students.get(i).setFirstName(newFirstName);
Related
Having some problems trying to call a method from a class.
Have my main method below
private static boolean findStudentId() {
System.out.println("Please enter your student ID to search for your profile");
int searchId = scanner.nextInt();
//need to be able to find a student's profile from the arraylist by searching their ID
return false;
}
I am trying to call a method from another class and cannot do so. this is my other class I am trying to call
public boolean findStudent(int id) {
for(int i = 0; i< students.size();i++)
{
if (students.equals(id)) {
System.out.println("Found the profile containing information for " + id);
// System.out.println(id.getFirstName()+id.getFirstName()+id.getLastName()+id.getDob());
return true;
} else
System.out.println("Could not find a profile based on the ID you provided");
}
return false;
}
this is my student class that I have created that proclaims the students
public class Student {
private int id;
private String firstName;
private String lastName;
private String dob;
public Student(int id,String firstName, String lastName, String dob) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.dob = dob;
}
public int getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getDob() {
return dob;
}
public static Student createStudentID(int id,String firstName, String lastName, String dob)
{
return new Student(id,firstName, lastName, dob);
}
}
I suggest to add a new class and put all the methods that you are going to be using in that class then in the main class create an object and you could easily use that methods with no problem
+small note the condition in findStudent method should be like
if (students.get(i).id == id)
so it would search for the id in the arraylist
If you want to call a method from another class you can for example create an object of the class you are trying to get the method from. For instance...
If the method you have is located inside of Class A, then create an object of that class.
A classAttribute = new A();
Then to call the method use....
classAttribite.someMethod();
is there any other way instead of using array list? in my assignment we are not allowed to use an array list, array is fine but not an array list at all ....basically it is a contact list book that saves 20 contacts. every contact has to be shown in alphabetical way.
main
public static void main(String[] args) {
List<Contact> lsCont = new ArrayList<Contact>();
Contact[] contacts = new Contact[20];
Scanner scanner = new Scanner(System.in);
String firstName;
String lastName;
String phone;
String email;
int maxContacts = 20;
for (int i = 0; i < contacts.length; i++) {
System.out.println("insert first name : ");
firstName = scanner.nextLine();
System.out.println("insert last Name : ");
lastName = scanner.nextLine();
System.out.println("insert phone : ");
phone = scanner.nextLine();
System.out.println("insert email : ");
email = scanner.nextLine();
Contact cont = new Contact(firstName, lastName, phone, email);
lsCont.add(cont);
Collections.sort(lsCont);
for (Contact contact : lsCont) {
System.out.println(contact.toString());
}
if (i == maxContacts) {
System.out.println("maxiumum number of adding contact has reached");
break;
}
}
}
}
Contact
public class Contact implements Comparable<Contact> {
private String firstName;
private String lastName;
private String phone;
private String email;
public Contact(String firstName, String lastName, String phone, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.phone = phone;
this.email = email;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getPhone() {
return phone;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setPhone(String phone) {
this.phone = phone;
}
#Override
public int compareTo(Contact obj) {
return this.lastName.compareTo(obj.lastName);
}
#Override
public String toString() {
return "Contacts: firstName = " + firstName + ", lastName = " + lastName + ", phone = " + phone + ", email = " + email;
}
}
If you know the size of Contact array then you can just go with array
public static void main(String[] args) {
int maxContacts = 20;
Contact[] contacts = new Contact[maxContacts]; // initialize array of size 20
Scanner scanner = new Scanner(System.in);
String firstName;
String lastName;
String phone;
String email;
//collect 20 contacts into array
for (int i = 0; i < maxContacts; i++) {
System.out.println("insert first name : ");
firstName = scanner.nextLine();
System.out.println("insert last Name : ");
lastName = scanner.nextLine();
System.out.println("insert phone : ");
phone = scanner.nextLine();
System.out.println("insert email : ");
email = scanner.nextLine();
contacts[i] = new Contact(firstName, lastName, phone, email);
}
// Just print contacts array is full
if (contacts.length == maxContacts) {
System.out.println("maxiumum number of adding contact has reached");
}
//Now just sort the array based on name
Arrays.sort(contacts);
//Finally print contacts in order
for (Contact contact : contacts) {
System.out.println(contact.toString());
}
}
I have an ArrayList which asks for user input then stores each employees details. How do I display everything stored in this ArrayList or search for a specific employee? How would I then edit or remove this employee from the ArrayList? I have two classes, one salesPerson - where I have all variables, setters, getters and constructors and salesPersonMain - where I have the prompting for user input, storing to an array etc.
I can add employees to the ArrayList and view them when I end the input loop.
public class salesPersonMain {
public static void main(String[] args) throws InputValidationException {
Scanner input = new Scanner(System.in);
List<salesPerson> sPerson = new ArrayList<salesPerson>();
while (true) {
System.out.println("Enter id (press 'q' to quit): ");
String temp = input.nextLine();
if (temp.equals("q")) break;
int id = Integer.parseInt(temp);
System.out.println("Enter first name:");
String firstName = input.nextLine();
System.out.println("Enter last name:");
String lastName = input.nextLine();
//save in array list
sPerson.add(new salesPerson(id, firstName, lastName));
}
for (salesPerson salesPerson : sPerson) {
System.out.println(salesPerson);
}
}
}
The salesPerson class:
import java.util.ArrayList;
public class salesPerson{
//create variables for sales person
private int id;
private String firstName;
private String lastName;
public salesPerson() {
}
//Setters and getters
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) throws InputValidationException {
if (firstName.matches("\\p{Upper}(\\p{Lower}){2,20}")) {
} else {
throw new InputValidationException();
}
{
this.firstName = firstName;
}
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName)throws InputValidationException {
if (lastName.matches("\\p{Upper}(\\p{Lower}){2,20}")) {
} else {
throw new InputValidationException();
}
{
this.lastName = lastName;
}
}
public void setCurrentCarMake(String currentCarMake) throws InputValidationException {
if (currentCarMake.matches("(\\p{Alpha}{2,14})")) {
} else {
throw new InputValidationException();
}
{
this.currentCarMake = currentCarMake;
}
}
public String getCurrentCarModel() {
return currentCarModel;
}
public void setCurrentCarModel(String currentCarModel) throws InputValidationException {
if (currentCarModel.matches("(\\p{Alnum}{1,10})")) {
} else {
throw new InputValidationException();
}
{
this.currentCarModel = currentCarModel;
}
}
//create constructor
public salesPerson(int id, String firstName, String lastName) throws InputValidationException {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
#Override
public String toString() {
return id + ", " + firstName + " " + lastName;
}
}
Well what you have tried will take care of searching part in List Of SalesPerson Object and display correcting. You can do little more modification like below code to handle remove part as well.
SalesPersonMain.java
public class SalesPersonMain {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
CopyOnWriteArrayList<SalesPerson> sPerson = new CopyOnWriteArrayList<>(); //List will fail in case of remove due to ConcurrentModificationException
while (true) {
System.out.println("Enter id (press 'q' to quit): ");
String temp = input.nextLine();
if (temp.equals("q")) break;
int id = Integer.parseInt(temp);
System.out.println("Enter first name:");
String firstName = input.nextLine();
System.out.println("Enter last name:");
String lastName = input.nextLine();
sPerson.add(new SalesPerson(id, firstName, lastName));
}
//Search
System.out.println("Enter String to search & display");
String searchString = input.nextLine();
for (SalesPerson salesPerson : sPerson) {
if(salesPerson.search(searchString)!=null){
System.out.println(salesPerson.toString());
}
}
//Remove
System.out.println("Enter String to search & remove");
searchString = input.nextLine();
for (SalesPerson salesPerson : sPerson) {
if(salesPerson.search(searchString)!=null){
System.out.println(salesPerson.toString()+" is removed from the List");
sPerson.remove(salesPerson);
}
}
//Display All
System.out.println("Final List : ");
for (SalesPerson salesPerson : sPerson) {
System.out.println(salesPerson.toString());
}
}
}
SalesPerson.java
public class SalesPerson {
public SalesPerson(Integer id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
Integer id;
String firstName;
String lastName;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
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;
}
#Override
public String toString() {
return "{" +
"'id':" + id +
", 'firstName':'" + firstName + '\'' +
", 'lastName':'" + lastName + '\'' +
'}';
}
public SalesPerson search(String search){
if(firstName.matches("(.*)"+search+"(.*)") || lastName.matches("(.*)"+search+"(.*)")){
return this;
}
return null;
}
}
Try the above code and hope you get the idea where to change what more.
Assuming a salesPerson class such as:
public class salesPerson {
private int id;
private String firstName, lastName;
public salesPerson() {}
public salesPerson(int id, String firstName, String lastName)
{
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public int getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public void setId(int id) {
this.id = id;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
You can do something like this to search for a specific to remove:
int searchIndex = 0;
for (int i = 0; i < sPerson.size(); i++) {
salesPerson currentPerson = sPerson.get(i);
//Prints current person
System.out.println(currentPerson.getId() + " " + currentPerson.getFirstName() + " " + currentPerson.getLastName());
if (currentPerson.getId() == 40) //Change 40 and getId to whatever you want to search for
{
searchIndex = i;
}
}
//The remove is outside the loop because you don't want to change the index during the loop or you might run into problems
sPerson.remove(searchIndex);
}
You can edit this to search for multiple values or throw it into a method with a parameter for search value etc.
When I run my program and choose option 2 to get contact details I am expecting it to display as follows (First Name, Last Name):
Contacts how have been entered:
0) John Doe
1) George Smith
2) Nancy Davis
Please enter the number corresponding to the contact you would like to view:
Instead for a personal contact it is displaying as follows:
Contacts who have been entered:
0) Doe 1 F St. (last name, address)
Please enter the number corresponding to the contact you would like to view:
Instead for a business contact it is displaying as follows:
Contacts who have been entered:
0) 1 F St. jd#gmail.com (address, email)
Please enter the number corresponding to the contact you would like to view:
Then when I enter the number to display the contact for personal it is returning me only first name and business is only returning me first and last name. It should be returning the full contact info that was put in during the add contact step. I thought I programmed everything properly but it isn't displaying what I want to see. Any help would be greatly appreciated. My code is listed below.
Main:
package contactlist;
import java.util.ArrayList;
import java.util.Scanner;
public class ContactList {
public static void main(String[] args) {
int swValue;
Scanner keyIn = new Scanner(System.in);
ArrayList<Contact> ContactRecords = new ArrayList<Contact>();
while (true) {
// Display menu graphics
System.out.println("========================================");
System.out.println("| Address List |");
System.out.println("========================================");
System.out.println("| Options: |");
System.out.println("| 1. Add Contact |");
System.out.println("| 2. Get Contact Details |");
System.out.println("| 3. Exit |");
System.out.println("========================================");
System.out.println(" Select option: ");
swValue = keyIn.nextInt();
switch (swValue) {
case 1:
addContact(ContactRecords);
break;
case 2:
getRecords(ContactRecords);
break;
case 3:
System.exit(0);
break;
default:
System.out.println("Invalid selection");
break;
}
}
}
public static void addContact(ArrayList<Contact> ContactRecords) {
Scanner textIn = new Scanner(System.in);
Scanner keyIn = new Scanner(System.in);
System.out.println("First Name: ");
String firstName = textIn.nextLine();
System.out.println("Last Name: ");
String lastName = textIn.nextLine();
System.out.println("Address: ");
String address = textIn.nextLine();
System.out.println("Email Address: ");
String email = textIn.nextLine();
System.out.println("Phone: ");
String phone = textIn.nextLine();
System.out.println("Is this a 1) Personal or 2) Business?");
int choice = keyIn.nextInt();
if (choice == 1) {
System.out.println("Date of Birth: ");
String dateOfBirth = textIn.nextLine();
Personal aPersonal = new Personal(firstName, lastName, address,
email, phone, dateOfBirth);
ContactRecords.add(aPersonal);
}
if (choice == 2) {
System.out.println("Job Title: ");
String jobTitle = textIn.nextLine();
System.out.println("Organization: ");
String organization = textIn.nextLine();
Business aBusiness = new Business(firstName, lastName, address,
email, phone, jobTitle, organization);
ContactRecords.add(aBusiness);
}
}
public static void getRecords(ArrayList<Contact> ContactRecords)
{
Scanner keyIn = new Scanner(System.in);
System.out.println("Contacts who have been entered:");
for (int i = 0; i < ContactRecords.size(); i++) {
System.out.println(i + ") "+ ContactRecords.get(i).getFirstName() +
" " + ContactRecords.get(i).getLastName();
}
System.out.println("Please enter the number corresponding to the contact
you would like to view: ");
int choice = keyIn.nextInt();
System.out.println(ContactRecords.get(choice).toString());
}
}
Contact
package contactlist;
public abstract class Contact {
private String firstName;
private String lastName;
private String address;
private String email;
private String phone;
public Contact(String firstName, String lastName, String address, String
email, String phone) {
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.email = email;
this.phone = phone;
}
public Contact() {
}
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 getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
#Override
public String toString() {
return toString() ;
}
}
Personal
package contactlist;
public class Personal extends Contact {
private String dateOfBirth;
public Personal(String dateOfBirth, String firstName, String lastName,
String address, String email, String phone) {
super(firstName, lastName, address, email, phone);
this.dateOfBirth = dateOfBirth;
}
public Personal() {
super();
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
#Override
public String toString() {
return dateOfBirth;
}
}
Business
package contactlist;
public class Business extends Contact {
private String jobTitle;
private String organization;
public Business(String jobTitle, String organization, String firstName,
String lastName, String address, String email, String phone) {
super(firstName, lastName, address, email, phone);
this.jobTitle = jobTitle;
this.organization = organization;
}
public Business() {
super();
}
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public String getOrganization() {
return organization;
}
public void setOrganization(String organization) {
this.organization = organization;
}
#Override
public String toString() {
return jobTitle + " " + organization;
}
}
This is the line you are using to print the contact:
System.out.println(ContactRecords.get(choice).toString());
This means you are using the toString() method to print the contact. Now, what do you have in a personal contact?
#Override
public String toString() {
return dateOfBirth;
}
This means it is only returning the date of birth, not any of the other fields in the contact.
For the business contact you have:
#Override
public String toString() {
return jobTitle + " " + organization;
}
This means it will only display the content of the fields jobTitle and organization, not any of the other fields.
This, in combination to the answer #femtoRgon gave you, which means that you are also not assigning the fields correctly, gives you the result you have.
You have to:
Change the toString() in Contact to return the common fields. Right now it is a dangerous, infinitely recursive method:
#Override
public String toString() {
return toString() ;
}
Rewrite the toString methods in the personal and business card so that they return a combination of super.toString() - the method you changed in step 1 - along with the additional fields that are specific to Personal or Business.
Change the new calls you make so that you pass the parameters correctly to the constructors.
Here are the Personal constructor call and the Personal constructor definition.
Personal aPersonal = new Personal(firstName, lastName, address,
email, phone, dateOfBirth);
public Personal(String dateOfBirth, String firstName, String lastName,
String address, String email, String phone) {
They order of your arguments doesn't match. So you are passing in a variable called "firstName" as the argument specified as the "dateOfBirth", and "lastName" as the "firstName", "address" as the "lastName", etc. So your call to the ctor should be:
Personal aPersonal = new Personal(dateOfBirth, firstName, lastName, address,
email, phone);
The problem is very much the same with your call to the Business constructor, you pass in "jobTitle" and "organization" as the last arguments, while the class expects them to be the first two arguments.
I'm doing a project with overloaded constructors in a class and I'm a little stuck, below is what I'm supposed to be doing with the overloaded constructors:
"One that allows first, middle, and last names to be passed as Strings with an int for age
One that accepts a Name object reference, and an age as an int
Make a new Name inside Person, copying the references for the parts of the name."
I'm not quite sure what to do with my code, here is what I got:
public class Person {
int age;
Name aPersonHasAName;
Name newPerson = new Name();
public Person(String firstName, String middleName, String lastName, int age) {
newPerson.firstName = firstName;
newPerson.middleName = middleName;
newPerson.lastName = lastName;
}
public Person(Name aPersonHasAName, int age) {
}
public void details() {
System.out.println(aPersonHasAName + " age: " + age);
}
}
I'm just lost as to what I'm supposed to be typing. I believe I've done the first overloaded constructor, but I am new to this.
So what should I be doing to make this work with overloaded constructors?
I think having the code from the other two classes might help.
Here is PersonTester:
public class PersonTester {
public static void main(String[] args) {
Person person1 = new Person("a1", "b1", "c1", 11);
Person person2 = new Person(new Name("a2", "b2", "c2"), 22);
Person person3 = new Person(new Name("a3", "c3"), 33);
Person person4 = new Person(new Name("a4"), 44);
Person person5 = new Person(new Name(), 55);
System.out.println(person1.details());
System.out.println(person2.details());
System.out.println(person3.details());
System.out.println(person4.details());
System.out.println(person5.details());
}
}
Then here is the Name class:
public class Name {
String firstName;
String middleName;
String lastName;
public Name(String firstName, String middleName, String lastName) {
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
}
public Name(String firstName, String lastName) {
this(firstName, "", lastName);
}
public Name(String firstName) {
this(firstName, "", "");
}
public Name() {
this("", "", "");
}
public String getLastName() {
return lastName;
}
public String getMiddleName() {
return middleName;
}
public String getFirstName() {
return firstName;
}
public String getFullName(String nameString) {
StringBuilder build = new StringBuilder();
build.append(nameString);
build.deleteCharAt(nameString.length() - 1);
build.insert(0, build.hashCode());
return build.toString();
}
}
The problem I am having now is the error message in PersonTester which is: The method println(boolean) in the type PrintStream is not applicable for the arguments (void)
I just need to know what in which class needs to be fixed to make it work.
I am very new to Java and object oriented programming.
So far so good. But eventually you'll reach a point where you duplicate a fair bit of code.
The constructor
public Person(String firstName, String middleName, String lastName, int age) {
is the most comprehensive one in the sense that it takes in all the possible data.
With the other constructors, say one that takes a last name and an age, you can use delegating constructors:
public Person(String lastName, int age) {
this(null, null, lastName, age); /*calls the other constructor*/
}
If you can't make such an assumption then you'll need to split up the name string by hand.
Updating your code:
public Person(String firstName, String middleName, String lastName, int age) {
newPerson.firstName = firstName;
newPerson.middleName =
newPerson.lastName = lastName;
this.age = age; //<---- was missing in your code
}
And your second contructor may look like this:
public Person(Name aPersonHasAName, int age) {
this.newPerson = aPersonHasAName;
this.age = age;
}
These contructors are implemented as you needed.
Notice that you already done your overloading, if you got multiple constructors with not the same titles you contructors overloading
public class Person {
int age;
Name aPersonHasAName;
public Person(String firstName, String middleName, String lastName, int age) {
aPersonHasAName = new Name();
aPersonHasAName.firstName = firstName;
aPersonHasAName.middleName = middleName;
aPersonHasAName.lastName = lastName;
this.age = age;
}
public Person(Name aPersonHasAName, int age) {
this.aPersonHasAName = aPersonHasAName;
this.age = age;
}
public void details() {
System.out.println(aPersonHasAName + " age: " + age);
}
}
I guess it also depends on if Name has a constructor for firstName, middleName, lastName