I need to write a code with a constructor class in order to see the whole phonelist using an array that reads from a document txt, able to add a person and phone number, search just one person in the phonelist and able to modify their phone number. here is my code
Constructor:

public class PhoneBookEntry {
    private String name;
    private String phone;

    public void setName(String n){
        name=n; 
    }
    public void setPhone(String p){
        phone=p;
    }
    public String getName(){
        return name;
    }
    public String getPhone(){
        return phone;
    }
    public String toString(){
        String str = "name " + name + "\n phone" + phone;
        return str;
    }
}

and here is the code that runs it

import java.util.Scanner;
import java.io.*;
public class PhoneBookEntryTest {

    /**
     *
     */
    public static void main(String[] args)throws IOException {
        // declaraciones
        final int SIZE = 10;
        String theName;
        int indexFound;
        Scanner kb = new Scanner(System.in);
        PhoneBookEntry[] phoneList = new PhoneBookEntry[SIZE];
        int entriesAmount=0;
        int select;
        entriesAmount = fillArrays(phoneList);
        do{
            System.out.println("Choose the corresponding number of your desired choice");
            System.out.println("1. See complete list");
            System.out.println("2. Add one person to the list");
            System.out.println("3. Look for a person in the list");
            System.out.println("4. Modify the phone number of one of the person ");
            System.out.println("5. Exit");
            System.out.println("Enter your selection");
            select = kb.nextInt();
            switch (select)
            { case 1: viewPhoneBook(phoneList,entriesAmount);
                        break;
              case 2: entriesAmount=insertEntry(phoneList,entriesAmount,kb);
                    break;
              case 3: kb.nextLine();
                   System.out.println("Enter the name you wish to find");
                   theName = kb.nextLine();
                   indexFound = searchPhone(theName,phoneList,entriesAmount);
                   if( indexFound == -1)
                      System.out.println("That name is not found. The format must be: LastName,FirstName");
                   else System.out.println(phoneList[indexFound]);
                   break;
            // case 4:
            case 5: updateFile(phoneList,entriesAmount);
                    System.out.println("Until next time.");
                    break;
            default: System.out.println("Error. Your entry selection must be 1, 2, 3, 4 or 5");
            }//end switch

        }while (select!= 5);

    }//end main
    public static int fillArrays(PhoneBookEntry[] myPhoneBook)throws IOException{
        File inFile = new File("Phonebook.txt");
        if(!inFile.exists()){System.out.println("file not found");
          System.exit(1);
        }
        Scanner fileReader = new Scanner(inFile);
        int c =0;
        while(fileReader.hasNext()&& c < myPhoneBook.length){
            String aName= fileReader.next();
            String aPhone= fileReader.nextLine();
            PhoneBookEntry tempEntry = new PhoneBookEntry();
            tempEntry.setName(aName);
            tempEntry.setPhone(aPhone);
            myPhoneBook[c] = tempEntry;
            c++;
        }//end while
        if(fileReader.hasNext()){
            System.out.println("There are still data in the file that can't fit into the array.");
            System.out.println("Contact your programmer");
            System.exit(2);
        }//end if

        fileReader.close();
        return c;
}
    public static int insertEntry(PhoneBookEntry[] myPhoneBook, int listAmount, Scanner kb){
        if(listAmount == myPhoneBook.length){
            System.out.println("Arrays are full. add operation cancelled.");
            return listAmount;
        }
        kb.nextLine();//clean buffer
        System.out.println("Enter the name");
        String aName = kb.nextLine();
        //check if that name is already in the list
        int indexFound = searchPhone(aName,myPhoneBook,listAmount);
        if (indexFound != -1)
            System.out.println("That name already exists, it can't be added.");
        else{myPhoneBook[listAmount].setName(aName);
        System.out.println("Enter the phone number(with dashes)");
        String aPhone=kb.nextLine();
        myPhoneBook[listAmount].setPhone(aPhone);
        listAmount++;}
        return listAmount;
}
    public static void updateFile(PhoneBookEntry[] myPhoneBook, int listAmount)throws IOException{
        PrintWriter phoneFile = new PrintWriter("Phonebook.txt");
        for(int k=0; k<listAmount; k++ )
            phoneFile.println(myPhoneBook[k]);
        phoneFile.close();
    }
    public static void viewPhoneBook(PhoneBookEntry[] myPhoneBook, int listAmount){
        System.out.println("Name & Phone List");
        for(int k=0; k<listAmount; k++ )
            System.out.println(myPhoneBook[k]);
    }
    public static int searchPhone(String searchName, PhoneBookEntry[] myPhoneBook, int listAmount){
        int foundPosition = -1;
        boolean found = false;
        int c =0;
        while(!found && c < listAmount)
            if (searchName.equals(myPhoneBook[c].getName())){
                found = true;
                foundPosition = c;
              }
            else c++;
        return foundPosition;

            }//end searchPhone

}

I still haven't written the code for number 4, but where I am asking help is in number 2 when i have to add the phone number it gives me an error message any help on number 2 would be great, and if u want to add your 2 cents on number 4 you're welcome to do so, but I'll see what i can do, the other ones work fine. Thanks.

Edited 3 Years Ago by gabriel.riveraperossenkopp

Ok, forget about it. I fixed the error.
it was here

public static int insertEntry(PhoneBookEntry[] myPhoneBook, int listAmount, Scanner kb){
        PhoneBookEntry tempEntry = new PhoneBookEntry();
        if(listAmount == myPhoneBook.length){
            System.out.println("Arrays are full. add operation cancelled.");
            return listAmount;
        }
        kb.nextLine();//clean buffer
        System.out.println("Enter the name");
        String aName = kb.nextLine();
        //check if that name is already in the list
        int indexFound = searchPhone(aName,myPhoneBook,listAmount);
        if (indexFound != -1)
            System.out.println("That name already exists, it can't be added.");
        else
        {   tempEntry.setName(aName);
            myPhoneBook[listAmount]=tempEntry;
            System.out.println("Enter the phone number(with dashes)");
            String aPhone=kb.nextLine();
            tempEntry.setPhone(aPhone);
            myPhoneBook[listAmount]=tempEntry;
            listAmount++;}
            return listAmount;

Edited 3 Years Ago by gabriel.riveraperossenkopp

actually, if your question was (which I thought it was) how to do that using a constructor, your question isn't solved, you just wrote a way 'around' it.

at this point, your class has no explicit added constructor, which means that the compiler will add the default (no argument) constructor for you.

if you want to do it using a constructor, just add an explicit constructor, which takes two arguments (both Strings) and set your values through them.

in your case, this could be something like:

public PhoneBookEntry(String name, String phone){
  this.name = name;
  this.phone = phone;
}

now you can create your instances using:

PhoneBookEntry newEntry = new PhoneBookEntry("John Doe","5552354");

do understand that if you add the above constructor to your PhoneBookEntry class, you can no longer create instances using:

PhoneBookEntry newEntry = new PhoneBookEntry();

unless you also explicitly add the code for the default constructor.

a remark on your other code, which I give quite frequently:

don't allow your main method to throw an Exception. there is nowhere to throw that Exception to. the main method is the very last place where you can add a bit of Exception handling, and avoid that your entire application crashes when an Exception occurs, in your code, as soon as an Exception is thrown, it's "game over".

yeah, i noticed, and changed some of the code, but I left the IOException because its reading the arrays from a .txt document and it won't allow me to use some of the methods without the IOException, but thanks again for your input, this is how I finished my code and it works perfectly. PS: I started coding last semester, this is my second semester coding in my university and I actually like it haha, but I'm still learning, of course.

import java.util.Scanner;
import java.io.*;
public class PhoneBookEntryTestApp2 {

    /**
     *
     */
    public static void main(String[] args)throws IOException {
        // declaraciones
        final int SIZE = 10;
        String theName;
        int indexFound;
        Scanner kb = new Scanner(System.in);
        PhoneBookEntry[] phoneList = new PhoneBookEntry[SIZE];
        int entriesAmount=0;
        int select;
        entriesAmount = fillArrays(phoneList);
        do{
            System.out.println("Choose the corresponding number of your desired choice");
            System.out.println("1. See complete list");
            System.out.println("2. Add one person to the list");
            System.out.println("3. Look for a person in the list");
            System.out.println("4. Modify the phone number of one of the person ");
            System.out.println("5. Exit");
            System.out.println("Enter your selection");
            select = kb.nextInt();
            switch (select)
            { case 1: viewPhoneBook(phoneList,entriesAmount);
                        break;
              case 2: entriesAmount=insertEntry(phoneList,entriesAmount,kb);
                    break;
              case 3: kb.nextLine();
                   System.out.println("Enter the name you wish to find");
                   theName = kb.nextLine();
                   indexFound = searchPhone(theName,phoneList,entriesAmount);
                   if( indexFound == -1)
                      System.out.println("That name is not found. The format must be: LastName,FirstName");
                   else System.out.println(phoneList[indexFound]);
                   break;
            case 4: kb.nextLine();
                    System.out.println("Enter the name of the person, you wish to edit the phone # ");  
                    theName=kb.nextLine();
                    indexFound = searchPhone(theName,phoneList,entriesAmount);
                    if( indexFound == -1)
                          System.out.println("That name is not found. The format must be: LastName,FirstName");
                    else
                    modifyPhone(phoneList[indexFound], kb);
                    break;
            case 5: updateFile(phoneList,entriesAmount);
                    System.out.println("Until next time.");
                    break;
            default: System.out.println("Error. Your entry selection must be 1, 2, 3, 4 or 5");
            }//end switch

        }while (select!= 5);

    }//end main
    public static int fillArrays(PhoneBookEntry[] myPhoneBook)throws IOException{
        File inFile = new File("Phonebook.txt");
        if(!inFile.exists()){System.out.println("file not found");
          System.exit(1);
        }
        Scanner fileReader = new Scanner(inFile);
        int c =0;
        while(fileReader.hasNext()&& c < myPhoneBook.length){
            String aName= fileReader.next();
            String aPhone= fileReader.nextLine();
            myPhoneBook[c] = new PhoneBookEntry(aName, aPhone);
            c++;
        }//end while
        if(fileReader.hasNext()){
            System.out.println("There are still data in the file that can't fit into the array.");
            System.out.println("Contact your programmer");
            System.exit(2);
        }//end if

        fileReader.close();
        return c;
}
    public static int insertEntry(PhoneBookEntry[] myPhoneBook, int listAmount, Scanner kb){
        if(listAmount == myPhoneBook.length){
            System.out.println("Arrays are full. add operation cancelled.");
            return listAmount;
        }
        kb.nextLine();//clean buffer
        System.out.println("Enter the name");
        String aName = kb.nextLine();
        //check if that name is already is in the list
        int indexFound = searchPhone(aName,myPhoneBook,listAmount);
        if (indexFound != -1)
            System.out.println("That name already exists, it can't be added.");
        else
        {   System.out.println("Enter the phone number(with dashes)");
            String aPhone=kb.nextLine();
            myPhoneBook[listAmount]=new PhoneBookEntry(aName, aPhone);
            listAmount++;}
            return listAmount;
}
    public static void updateFile(PhoneBookEntry[] myPhoneBook, int listAmount)throws IOException{
        PrintWriter phoneFile = new PrintWriter("Phonebook.txt");
        for(int k=0; k<listAmount; k++ )
            phoneFile.println(myPhoneBook[k]);
        phoneFile.close();
    }
    public static void viewPhoneBook(PhoneBookEntry[] myPhoneBook, int listAmount){
        System.out.println("Name & Phone List");
        for(int k=0; k<listAmount; k++ )
            System.out.println(myPhoneBook[k]);
    }
    public static int searchPhone(String searchName, PhoneBookEntry[] myPhoneBook, int listAmount){
        int foundPosition = -1;
        boolean found = false;
        int c =0;
        while(!found && c < listAmount)
            if (searchName.equalsIgnoreCase(myPhoneBook[c].getName())){
                found = true;
                foundPosition = c;
              }
            else c++;
        return foundPosition;

            }//end searchPhone
    public static void modifyPhone(PhoneBookEntry phoneList, Scanner kb){
        System.out.println("Edit the phone number now ");
        String ePhone=kb.nextLine();
        phoneList.setPhone(ePhone);
    }
}

Edited 3 Years Ago by gabriel.riveraperossenkopp

yes, I know you need to handle it, but a better approach would be:

public static void main(String[] args){
  try{

    // your code here

  } catch(IOException ioe){
    System.out.println("IOException caught: " );
    ioe.printStackTrace();
  } catch(Exception e){
    System.out.println("Exception caught: ");
    e.printStackTrace();
  }
}

this way, your code still compiles and works, but you can add exception handling in the catch block(s). that way you can 'gracefully' terminate your application, even if an Exception is thrown. That 's not possible if you allow your main method to throw the Exception.

how about if entry is already exist it would be warn to user about it...

how about if entry is already exist it would be warn to user about it...

why?because we have a proram that will create a phonebook,wherein you can add **entries in the phonebook,delete** entries,View all entries and Search **entries.In viewing all entries, the user should have a choice,whether to view the entries in **alphabetical order or in increasing ** order of the telephone number.In searching for entries, the user should also have an option to search entries **by name or by telephone numbers.In searching by name, the user should also have an option if he /she wants to search by first name or last name.

because it's not part of the OP's assignment, that's why. same reason cars don't have to fly, they do what they're supposed to do.
now, I don't know whether or not you've noticed, but this thread has been marked as 'solved', which means you shouldn't keep posting in here. the only reason I did was to give a remark on some part of the original code. you're just hijacking this thread to ask your own questions.

if you really feel like asking them, start a new thread.

This question has already been answered. Start a new discussion instead.