I need to remove an element from an ArrayList using user's input.
Not really asking for a solution, but more of a guide in the right direction.
public class BFFHelper
{
ArrayList<BestFriends> myBFFs;
Scanner keyboard = new Scanner(System.in);
public BFFHelper()
{
myBFFs = new ArrayList<BestFriends>();
}
public void addABFF()
{
System.out.println("Enter a first name: ");
String firstName = keyboard.next();
System.out.println("Enter a last name: ");
String lastName = keyboard.next();
System.out.println("Enter a nick name: ");
String nickName = keyboard.next();
System.out.println("Enter a phone number: ");
String cellPhone = keyboard.next();
BestFriends aBFF = new BestFriends(firstName, lastName, nickName, cellPhone);
myBFFs.add(aBFF);
}
public void changeABFF()
{
System.out.println("I am in changeBFF");
}
public void removeABFF()
{
//System.out.println("I am in removeABFF");
System.out.print("Enter friend's name to remove: ");
int i = 0;
boolean found = false;
while (i<myBFFs.size() && !found)
{
if (myBFFs.get(1).getfirstName().equalsIgnoreCase(firstName)) && (myBFFs.get(1).hetlastName().equalsIgnoreCase(lastName))
i++
}
}
public void displayABFF()
{
System.out.println("My Best Friends Phonebook is: ");
System.out.println(myBFFs);
}
}
this is what i have for my main class
public class BestFriends {
private static int friendNumber = 0;
private int friendIdNumber;
private String firstName;
private String lastName;
private String nickName;
private String cellPhoneNumber;
public BestFriends (String aFirstName, String aLastName, String aNickName, String aCellPhone)
{
firstName = aFirstName;
lastName = aLastName;
nickName = aNickName;
cellPhoneNumber = aCellPhone;
friendIdNumber = ++friendNumber;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public String getNickName()
{
return nickName;
}
public String getCellPhone()
{
return cellPhoneNumber;
}
public int getFriendId()
{
return friendIdNumber;
}
public String toString()
{
return friendIdNumber + ". " + firstName + " (" + nickName + ") " + lastName + "\n" + cellPhoneNumber + "\n";
}
}
Elements can be removed from an ArrayList using in various ways, for example by calling list.remove(index); or alternatively, by simply specifying the object to remove.
Just study the Javadoc for those methods. In addition to that, there are calls like removeAll() that remove all the arguments provided to the call.
Side note: there is at least one bug in your code:
if (myBFFs.get(1).getfirstName().equalsIgnoreCase(firstName)) && (myBFFs.get(1).hetlastName().equalsIgnoreCase(lastName))
should probably read.
if (myBFFs.get(i).getfirstName().equalsIgnoreCase(firstName)) && (myBFFs.get(i).hetlastName().equalsIgnoreCase(lastName))
Assuming that you are looping with i for a reason; and that you don't want to compare element1 to itself all the time.
And while we are at it: you could improve your abstractions. Obviously your program is about "humans". Humans normally have fixed names, haven't they. Meaning: have a class that just represents a human being; with final fields for information that can't change. Such fields are initialized via the constructor; and you dont have any setters for those.
How to Remove element of ArrayList from user's input?
One way to do such thing is to use an Iterator and call remove() when you find a match, something like this:
// Iterate over the list myBFFs
for (Iterator<BestFriends> it = myBFFs.iterator(); it.hasNext();) {
BestFriends bf = it.next();
if (/*some test here*/) {
// Found a match to remove
it.remove();
// Exit from the loop
// To be added if and only if you expect only one match otherwise keep iterating
break;
}
}
Assuming that you use Java 8, you can rely on the Stream API for such need.
In case you want to remove the first match
myBFFs.stream().filter(bf -> /*some test here*/).findFirst().ifPresent(myBFFs::remove);
This approach uses List#remove(Object o) to remove a unique object.
In case you want to remove all matches
myBFFs.removeAll(
myBFFs.stream().filter(bf -> /*some test here*/).collect(Collectors.toList())
);
This approach uses List#removeAll(Collection c) to remove a collection of objects.
Related
This question already has answers here:
How to convert an Array to a Set in Java
(19 answers)
Closed 2 years ago.
In my task I already put some cities in array but I now face a problem.
In main i did this:
City[] cities = enterCity(scanner);
In method enter city I had array of 3. So I needed to return name of a city and number of citizens.
In for loop I enter name and number of citizens. At the end of loop I did this:
cities[i]=new City(name, numbersOfCitizens);
and then returned it with City[] cities.
Now I need to improve my code with set.
In method I implemented:
Set<City> cities = new Hashset<>();
I failed to create method add. I tried with this to call it in main:
add.(City(name, numbersOfCitizens));
in City class and return City[] cities says inconvertible types ( so it cannot return anything). Is the right thing to call method like I do in main and if it is how to properly return all values. In class City I have usual get and set method.
Create Set
// Create new Set
Set<City> cities = new HashSet<City>();
// Add new City
cities.add(new City());
Convert Set in to array - option #1
City[] objects = cities.toArray(new City[0]);
Convert Set in to array - option #2
Manual copy:
City[] objects = new City[cities.size()];
int position = 0;
for (City city : cities) {
objects[position] = city;
position++;
}
Working example
public class SetExample {
private static Scanner scanner;
public static void main(String[] args) {
scanner = new Scanner(System.in);
Set<City> cities = readCities();
}
private static Set<City> readCities() {
Set<City> cities = new HashSet<City>();
int numberOfCities = 3;
for (int i = 0; i < numberOfCities; i++) {
City newCity = readCity();
cities.add(newCity);
}
return cities;
}
private static City readCity() {
System.out.print("Name: ");
String name = scanner.nextLine();
System.out.print("Numbers of citizens: ");
int numbersOfCitizens = scanner.nextInt();
return new City(name, numbersOfCitizens);
}
}
Printing
Example of the class:
class City {
private String name;
private int numbersOfCitizens;
public City(String name, int numbersOfCitizens) {
this.name = name;
this.numbersOfCitizens = numbersOfCitizens;
}
}
When you will use without adding toString() method so:
City city = new City("New York", 1234);
System.out.println(city);
you can expect output:
City#19469ea2
To print custom message, you have to override toString() method, for example generate "default" method in IntelliJ:
#Override
public String toString() {
return "City{" +
"name='" + name + '\'' +
", numbersOfCitizens=" + numbersOfCitizens +
'}';
}
or something simple like:
#Override
public String toString() {
return name + " " + numbersOfCitizens;
}
I am relatively new to programming and an working with setters and getters at the moment.
I have something set up where I have a student class that has information about said student, including their first, middle, and last name, their student ID, and their major.
I need to set it so that, if their student ID is less than zero, it automatically sets it to -1. I also need to set the major to undecided if they do not input anything.
I also need to override the toString method and print all of this information out.
I feel like I have the first part with the names down, I am not sure about the rest of it however. I am not sure how I am supposed to use the toString method while also using setters and getters.
Below is my Student class that does all of the work.
import java.util.Objects;
import java.util.Scanner;
public class Student {
String first;
String middle;
String last;
String major = "Undecided";
static int studentID = -1;
public Student(String first, String middle, String last) {
Objects.requireNonNull(first);
Objects.requireNonNull(last);
}
public void setFirst(String A) {
first = A;
}
public void setMiddle(String B) {
middle = B;
}
public void setLast(String C) {
last = C;
}
private String getFirst() {
return first;
}
private String getMiddle() {
return middle;
}
private String getLast() {
return last;
}
private String getMajor() {
return major;
}
public void setMajor(){
static void register(int a){
if (a < 0) {
studentID = a;
} else {
studentID = getID(a);
}
}
private static int getID(int a) {
if (studentIDInput < 0) {
studentID = -1;
} else {
studentID = a;
}
return studentID;
}
public static void main(String[] args) {
String first = "abc";
String middle = "def";
String last = "ghi";
Scanner sc = new Scanner(System.in);
String majorInput = sc.next();
int studentIDInput = sc.nextInt();
Student student1 = new Student(first, middle, last);
System.out.println(student1.getFirst().toString() + " " + student1.getMiddle().toString() + " " + student1.getLast().toString() + '\n' + "Major:" + " " + student1.getMajor().toString() + '\n' );
}
#Override
public String toString() {
return ;
}
}
I have also included the Driver class just for reference.
public class Driver {
static String first;
static String middle;
static String last;
public static void main(String[] args){
Student student1 = new Student(first, middle, last);
student1.setFirst("Mikayla");
student1.setMiddle("Rose");
student1.setLast("Knox");
}
}
You have this constructor:
public Student(String first, String middle, String last) {
Objects.requireNonNull(first);
Objects.requireNonNull(last);
}
It does its job of checking that first and last name are not null, but it does not do anything with the values besides checking. The constructor's job is to construct the object, i.e, initialize its member variables. When your constructor is done, you should have a usable object, without having to call any setters in it.
You need to add that:
public Student(String first, String middle, String last) {
Objects.requireNonNull(first);
Objects.requireNonNull(last);
this.first = first;
this.middle = middle;
this.last = last;
}
Note that you don't need to use setters here as code within the class can access member variables directly. You can use setters if you want, though.
As for toString: this is a method mainly used in debugging, and it displays some helpful information about the object it's called on. You could implement it like below, with a bit of ?: to make sure to only print the middle name if it's not null:
#Override
public String toString() {
return first + " " + (middle != null ? middle + " " : "") + last;
}
I'll leave it to you to also include major and ID.
On using a Scanner: You use a Scanner to get input from somewhere, like the from the user. You don't need it in toString or any setters or getters. These are all methods that should be very simple and not deal with I/O classes like Scanner.
If you are using constructors, you do not really need setters. Try something like this:
class Student {
private String first;
private String middle;
private String last;
private String major;
private int studentID;
public Student(String first, String middle, String last) {
this(first, middle, last, "undecided", -1);
}
public Student(String first, String middle, String last, String major, int studentID) {
this.first = first;
this.middle = middle;
this.last = last;
this.major = major;
this.studentID = studentID;
}
#Override
public String toString() {
return "first: " + first + "\nmiddle: " + middle + "\nlast: " + last + "\nmajor: " + major + "\nid: " _ studentID;
}
}
This way, when you create a new Student object with 3 parameters, the last 2 are automatically set to "undecided" and -1. If there is a case when you have the ID and not the major (or the other way around), you can add more constructors.
i hope someone can help me, i'm struggling with this since yesterday...
I'm working right now on a Hotel Management System project.
What i'm trying to do is, to put an array[] Clients into an ArrayList of Rooms and then set this room attribute to 'occupied = true' and save that so if i try to use that room for other client it doesn't let me.
Room class
public class Room {
private int number;
private float price= 30.5f;
private boolean occupied = false;
private Client[] hosts;
public Room(int number, Client[] hosts) {
this.number= number;
this.hosts= hosts;
}
public void setOccupied() {
this.occupied = true;
}
}
Client class
public class Client {
private String id;
private String name;
private String lastName;
public Client(String id, String name, String lastName) {
this.id = id;
this.name= name;
this.lastName= lastName;
}
}
This is what i've got on my Main so far... i'm calling the next function
public void checkIn(ArrayList<Room> myRooms){
int roomNumber;
String id;
String name;
String lastName;
Scanner input = new Scanner(System.in);
int people = input.nextInt();
Client[] array = new Client[people];
for (int i = 0; i < people; i++) {
System.out.println("Enter ID" + (i+1));
id = input.next();
System.out.println("Enter name " + (i+1));
name= input.next();
System.out.println("Enter last name " + (i+1));
lastName= input.next();
array[i] = new Client(id,name,lastName);
}
System.out.print("Assign to room number... : ");
roomNumber = input.nextInt();
myRooms.add(new Room(roomNumber, array));
//here i tried doing:
//room.set().setOccupied();
//room.set(roomNumber).setOccupied();
//but .set() expects an index...
}
Once i have this, i want to create a function that shows a list of rooms that are occupied
Excuse my english since i'm Spanish
Several ways to tackle this, probably what i would do is overload my room constructor so that you can set if it's occupied or not once you instantiate it like:
public Room(int number, Client[] hosts, boolean occupied)
{
this.number = number;
this.hosts = hosts;
this.occupied = true;
}
and in your checkIn() method just add true when instantiating your room inside the list:
myRooms.add(new Room(roomNumber, array, true));
Since you aren't creating a reference-able instance of Room when you call
myRooms.add(new Room(roomNumber, array));
you can't then say
room.setOccupied();
You can fix this two ways: First, as Bahij.Mik said, you could call this.occupied = true; in the Room constructor. Or, you could simply create a new instance of a Room in your checkIn method. This would look like:
Room newRoom = new Room(roomNumber, array);
newRoom.setOccupied();
whenever someone checks in.
As for creating a function to check which rooms are occupied, make an array of room numbers and then try:
public String[][] findOccupiedRooms(int[] roomNumbers) {
String[][] roomList = new String[roomNumbers.length][1];
for(int i = 0; i < roomNumbers.length; i++) {
if(roomNumbers[i].isOccupied() == true) {
roomList[i][0] = "" + roomNumbers[i];
roomList[i][1] = "occupied";
} else {
roomList[i][0] = "" + roomNumbers[i];
roomList[i][1] = "vacant";
}
}
return roomList[][];
}
This returns a 2-dimensional array that stores the room number and whether it is occupied or vacant. Not sure if this is exactly what you are looking for, but I hope it helps.
I want to create a program which displays current staff in the ArrayList before asking the user for input of a payroll number they'd like to remove. User then should input the payroll number of one of the three staff members and press enter. Upon pressing enter, the program should remove that particular staff member from the array list and display the entire list again (missing out the staff member they've deleted obviously). If the user no longer wishes to remove any payroll numbers, the payroll number entry should be 0 and should then display the contents of the list again.
The problem I'm having is with the remove part.
I've been recommended of two ways of achieving this:
This 'search' method should return either the position within the ArrayList (so that remove(<index>) may be used) or a reference to the object (so that remove(<objectRef>) may be used). If the staff member is not found, then the search method should return -1 (if remove(<index>) is being used) or null (if remove(<objectRef>) is being used).
However I am not sure how to implement this in Java.
Here is my file structure:
ArrayListTest.java
import java.util.*;
import personnelPackage.Personnel;
public class ArrayListTest
{
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args)
{
long searchQuery;
ArrayList<Personnel> staffList = new ArrayList<Personnel>();
Personnel[] staff =
{new Personnel(123456,"Smith","John"),
new Personnel(234567,"Jones","Sally Ann"),
new Personnel(999999,"Black","James Paul")};
for (Personnel person:staff)
staffList.add(person);
do
{
showDisplay(staffList);
System.out.print("\nPlease enter a payroll number to search: ");
searchQuery = keyboard.nextLong();
searchForPayrollNumber(staffList, searchQuery);
}while(!(searchQuery == 0));
}
private static void showDisplay(ArrayList<Personnel> staffList)
{
System.out.print("\n------------- CURRENT STAFF LIST -------------\n");
for (Personnel person : staffList)
{
System.out.println("Payroll number: " + person.getPayNum());
System.out.println("Surname: " + person.getSurname());
System.out.println("First name(s): " + person.getFirstNames() + "\n");
}
}
public static void searchForPayrollNumber(ArrayList<Personnel> staffList, long searchQuery)
{
long index = staffList.indexOf(searchQuery);;
for (Personnel person: staffList)
{
if (person.getPayNum() == searchQuery)
{
System.out.print("\n------------- Staff member found and removed! -------------");
System.out.println("\n\nFirst Name(s): " + person.getFirstNames());
System.out.println("\nSurname: " + person.getSurname());
System.out.print("\n-----------------------------------------------");
staffList.remove(index);
return;
}
}
System.out.print("\n------------- No staff members found. Program terminated -------------");
return;
}
}
Personnel.java (in its own package named personnelPackage)
package personnelPackage;
public class Personnel
{
private long payrollNum;
private String surname;
private String firstNames;
public Personnel(long payrollNum, String surname, String firstNames)
{
this.payrollNum = payrollNum;
this.surname = surname;
this.firstNames = firstNames;
}
public long getPayNum()
{
return payrollNum;
}
public String getSurname()
{
return surname;
}
public String getFirstNames()
{
return firstNames;
}
public void setSurname(String newName)
{
surname = newName;
}
}
Consider using Iterator for search and removal:
Iterator<Personnel> i = staffList.iterator();
while (i.hasNext()) {
Personnel p = i.next();
if (p.getPayNum() == searchQuery) {
// print message
i.remove();
return p;
}
}
return null;
If using List#remove() is strictly required, return found personnel p and call if (p != null) staffList.remove(p):
public static Personnel searchByPayNum(List<Personnel> ps, long num) {
for (Personnel p : ps) {
if (p.getPayNum() == num)
return p;
}
return null;
}
And in caller code:
Personnel p = searchByPayNum(staffList, query);
if (p != null) {
// log
staffList.remove(p);
}
public static long searchForPayrollNumber(ArrayList<Personnel> staffList, long searchQuery) {
//long index = staffList.indexOf(searchQuery);
for(int i = 0; i < staffList.size(); i++) {
if (staffList.get(i).getPayNum() == searchQuery) {
System.out.print("\n------------- Staff member found and removed! -------------");
System.out.println("\n\nFirst Name(s): " + staffList.get(i).getFirstNames());
System.out.println("\nSurname: " + staffList.get(i).getSurname());
System.out.print("\n-----------------------------------------------");
//staffList.remove(i);
return i;
}
}
System.out.print("\n------------- No staff members found. Program terminated -------------");
return -1;
}
Your search method shouldn't return void. It should return int or long instead,
public static long searchForPayrollNumber(ArrayList<Personnel> staffList, long searchQuery)
{
int index = -1;
for (int i = 0; i < staffList.size(); i++){
if(staffList.get(i).getPayNum() == searchQuery){
index = i;
System.out.print("\n------------- Found Staff member at position " + index + " in the list");
break;
}
}
if (index != -1){
staffList.remove(index);
System.out.print("\n------------- Removed the staff member");
}
return index;
}
Last approach returned the index. Now when you want to return the object:
public static long searchForPayrollNumber(ArrayList<Personnel> staffList, long searchQuery)
{
Personnel p = null;
for (int i = 0; i < staffList.size(); i++){
if(staffList.get(i).getPayNum() == searchQuery){
p = staffList.get(i);
break;
}
}
staffList.remove(p);
return p;
}
You must know that after removing it from the list, It will shift any subsequent elements to the left (subtracts one from their indices).
Also, just a suggestion:
Instead of
Personnel[] staff =
{new Personnel(123456,"Smith","John"),
new Personnel(234567,"Jones","Sally Ann"),
new Personnel(999999,"Black","James Paul")};
Why not
staffList.add(new Personnel(123456,"Smith","John"));
staffList.add(new Personnel(234567,"Jones","Sally Ann"));
staffList.add(new Personnel(999999,"Black","James Paul"));
This is just an advice. Since searching and removing are your primary goals, ArrayList is not the right collection to use.
Create a Hashmap with ID as key and Personnel object as value. This will help in identifying the Personnel in O(1) time and removal as well.
ArrayList should be used only when you know the index to read value. It then does that in O(1). If not, it is O(n) and not as efficient as HashMap.
I want to solve this problem without using arraylist.
i want to add the contact to its specific index in the array of strings. And then display all the added contacts in string format seperated by commas.
My code gives the result of only last added contract:
Contact [first=Bob, last=Moore, number=555-9756]
where is the problem in my code?
Is there any idea how to solve???
This class consist of the main method:
This is the main class:
public class ExampleApp {
public static void main(String[] args) {
PhoneBook pb = new PhoneBook("Personal book");
System.out.println( pb.getName() );
pb.add("Alice", "Green", "555-1234");
pb.add("Mary", "Smith", "555-6784");
pb.add("Bob", "Moore", "555-9756");
System.out.println( pb.toString() );// here i want to display all the contracts seperated by commas
System.out.println( pb.first() );// first contract
System.out.println( pb.get(2) );// second contract
String toBeFound = new String("Moore");
System.out.println( pb.find(toBeFound) );// display the found contract
}
}
This is the phonebook class:
public class PhoneBook {
public static final int MAX = 10;
public String name;
String[] contracts = new String[MAX]; // i created an array of strings
Contact c;
/**
* Create a new phonebook with given name
*/
public PhoneBook(String name) {
this.name = name;
}
/**
* Return the phonebook name
*/
public String getName() {
return name;
}
/**
* Insert a new contact at the end
*/
public void add(String first, String last, String number){
c=new Contact(first,last,number);
for(int i=0;i<MAX;i++){ // i added for each array index the contracts strings
contracts[i]= c.toString();
}
}
/**
* Return the first contact
*/
public String first() {
return get(1);
}
/**
* Return the i-th contact (supposing that first
* index is 1)
*/
public String get(int i) {
String s =contracts[i].toString();
return s;
}
/**
* Return a string containing the list of textual
* representation of all contacts, separated by ", ".
* List starts with "("and ends with ")"
*/
public String toString() {
String s= " ";
for(int i=1;i<MAX;i++){ // here i tried to display the string looping the array
s=contracts[i].toString();
}
return s;
}
/**
* Return the textual representation of first
* contact containing "needle"
*/
public String find(String needle) {
//TODO: to be implemented
return null;
}
}
This is the contact class :
public class Contact {
public String first;
public String last;
public String number;
public String[] contacts;
public Contact(String first, String last, String number) {
this.first=first;
this.last = last;
this.number=number;
}
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
}
public String getLast() {
return last;
}
public void setLast(String last) {
this.last = last;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
#Override
public String toString() {
return "Contact [first=" + first + ", last=" + last + ", number="
+ number + "]";
}
}
You can use ArrayList for it. It will help you really much and you should make your veriables private.
private String first;
private String last;
private String number;
private ArrayList<String> list = new ArrayList<String>();
for(String pointer : list){
}
or you can make contact saver ArrayList
private ArrayList<Contact> list = new ArrayList<Contact>();
public Contact(String first, String last, String number) {
this.first=first;
this.last = last;
this.number=number;
}
public void add(String first, String last, String number){
c=new Contact(first,last,number);
list.add(c);
}
and you can access all veriables like that list.get(i).first.
You can save your contact class and contracts array in arraylist and it will give you more power to access. If you want to display your ArrayList, which index is not important, you need only ++i for it.
I changed your class look this:
public class PhoneBook {
public static final int MAX = 10;
public String name;
String[] contracts = new String[MAX]; // i created an array of strings
Contact c;
private int count = 0;// saved last index of array
public PhoneBook(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void add(String first, String last, String number) {
c = new Contact(first, last, number);
contracts[count] = c.toString(); // save your String inside of last index++
count++;
}
public String first() {
return get(1);
}
public String get(int i) {
String s = contracts[i].toString();
return s;
}
public String toString() {
for (int i = 0; i < MAX; i++) {
if (contracts[i] != null)
System.out.println(contracts[i].toString());
}
return "";
}
public String find(String needle) {
return null;
}
}
public class Contact {
public String first;
public String last;
public String number;
public Contact(String first, String last, String number) {
this.first = first;
this.last = last;
this.number = number;
}
#Override
public String toString() {
return "Contact [first=" + first + ", last=" + last + ", number="
+ number + "]";
}
}
//Personal book
//Contact [first=Alice, last=Green, number=555-1234]
//Contact[first=Mary, last=Smith, number=555-6784]
//Contact [first=Bob, last=Moore, number=555-9756]
you always delete your last toString method. Your Add method is wrong. You always turn 0 and write again inside of array.
You should keep track of the last contact added to your array :
private int lastIndex = 0; // index of first available index of the array
...
/**
* Insert a new contact at the end
*/
public void add(String first, String last, String number){
c=new Contact(first,last,number);
if (lastIndex < MAX)
contracts[lastIndex++]= c.toString();
}
Some other issues with your code :
/**
* Return the first contact
*/
public String first() {
return get(1); // should be get(0)
}
Calling toString() for contracts[i] is redundant, since it's already a String. Perhaps you meant to store Contact instances instead of Strings in your array? That would make more sense.
Add an extra variable static int Last = 0; To track how many contact you have added and update the add function as .
public void add(String first, String last, String number){
if(Last>=MAX){
System.out.println("Error in adding\n");
}
else{
c=new Contact(first,last,number);
contacts[Last] = c.toString();
Last++;
}
}
Change Tostring() for loop to last. So that you will be printing only added contact .In your case you are printing upto MAX that is wrong when less no of contacts are added.
You have to pass i=0,1,2,...,MAX-1 to get(i) function . Array is Zero(0) based indexed.
So, the problem you are having is that you always retrieve the last contact, regardless of which one you try to get. This is because when you add a new contact, you are actually replacing ALL the contacts, making them all the same. You are getting the correct contact from the phonebook, but they ALL have the same value.
To fix it, do the following:
public class PhoneBook
{
int contactsAdded = 0; // Add an integer to store how many contacts you have added
Contact[] contacts = new Contact[MAX]; //Change this to Contact array, not string
//Contact c; //You can remove this line
//Rest of your code
}
public void add(String first, String last, String number)
{
//Only add if the number of contacts is less than the max
if (contactsAdded < MAX)
{
//Construct the new contact when you use it.
contacts[contactsAdded] = new Contact(first, last, number);
contactsAdded++;
}
}
Not sure if I understood all of your code right, but I think you are overwriting all other contacts in your phone book:
public void add(String first, String last, String number){
c=new Contact(first,last,number); //(1)
for(int i=0;i<MAX;i++){ //(2)
contracts[i]= c.toString();
}
}
At position (1) a new Contact object is created and assigned to c. In the next step (2), you loop through the array and assign the info contained in c (the latest contact added) to all already entries in the contracts array.
Independent from your problem, I suggest that you replace the array of a fixed size with i.e. an ArrayList of type Contact. Adding entries to this list, iterating, sorting etc is very easy.