Question

Fix the following null pointer error. import java.util.*; import java.io.*; public class PhoneBook { public static...

Fix the following null pointer error.

import java.util.*;

import java.io.*;

public class PhoneBook {

public static void main(String[]args)throws IOException {

PhoneBook obj = new PhoneBook();

PhoneContact[]phBook = new PhoneContact[20];

Scanner in = new Scanner(System.in);

obj.acceptPhoneContact(phBook,in);

PrintWriter pw = new PrintWriter("out.txt");

obj.displayPhoneContacts(phBook,pw);

pw.close();

}

public void acceptPhoneContact(PhoneContact[]phBook, Scanner k) { //void function that takes in the parameters

//phBook array and the scanner so the user can input the information

//declaring these variables

String fname = "";

String lname = "";

String contact = "";

String option = "";

System.out.println("Do you have any new contacts to enter? Enter zzz to exit. ");

option = k.next(); //enter yes or no and the output is stored in the option variable

int count = 0; //initialize count to 0

if(phBook[0] != null) { //this checks if the phBook is empty or not

count = getCurrentContactCount(phBook); //if yes, it will display an integer and value assigned to count

}

else {//if not, the phone book is empty and a message will be displayed saying that its empty

System.out.println("Phone book is empty");

count = 0;

}

while(!(option.contentEquals("zzz")) && count <= 20) { //while loop that will continue to ask

//the user for more contacts if there are not 20 contacts already and if the user does not enter zzz

System.out.println("Enter first name: ");

fname = k.next(); //after entering in the name; it stores it in the fname variable

System.out.println("Enter last name: ");

lname = k.next();

System.out.println("Enter phone number: ");

contact = k.next();

if(option.contentEquals("zzz")) {

break;

}

if(phBook[0] != null) { //if this is not empty it will look for a contact

if(searchContact(phBook, fname, lname, contact) != null) {//if this is not empty, it'll say the contact exists

System.out.println("Contact exists");

System.out.println(searchContact(phBook, fname, lname, contact));

break;

}else {//otherwise it will add the contact to the phone book

phBook[count] = new PhoneContact(fname, lname, contact);

count++;

if(count >= 20) {

System.out.println("You have reached the maximum number of contacts.");

break;

}

}

}

else {//if the phone book array is empty then it will print that the phone book is empty and add the contact

System.out.println("Phone book is empty");

phBook[count] = new PhoneContact(fname, lname, contact);

count++;

}

System.out.println("Do you have any new contacts to enter? ");

option = k.next();

}//ends while loop; if the user wants to exit and no longer enter in contacts they will type zzz

System.out.println("The phone book has " + count + " contacts");

}

public int getCurrentContactCount(PhoneContact[]phBook) {

int numContacts = 0;

for(int a = 0; a < phBook.length; a++) {

if(phBook[a] != null) {

numContacts++;

}

}

return numContacts;

}

public PhoneContact searchContact(PhoneContact[]phBook, String fname, String lname, String phone) {

PhoneContact contact= null;

for(int a= 0 ; a < phBook.length ; a++) {

if(phBook[a] != null && phBook[a].getfirstName().equals(fname)) {//compare lname and phone contact

System.out.println("Phone book conatct exists");

contact = phBook[a];

break;

}

}

return contact;

}

public void displayPhoneContacts(PhoneContact[]phBook, PrintWriter pw)

throws IOException{

pw.println("Phone Book");

pw.println("**************************");

pw.print("First Name\tLast Name\t Contact number");

for(int a= 0 ; a < phBook.length ; a++) {

pw.println(phBook[a].getfirstName() +"\t" + phBook[a].getlastName()+"\t" + phBook[a].getphoneNumber());

}

}

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

import java.util.*;
import java.io.*;

class PhoneContact{
   String fname,lname,phoneNum;
   PhoneContact(String f,String l,String c){
       this.fname=f;
       this.lname=l;
       this.phoneNum=c;
   }
   public String getFname() {
       return fname;
   }
   public void setFname(String fname) {
       this.fname = fname;
   }
   public String getLname() {
       return lname;
   }
   public void setLname(String lname) {
       this.lname = lname;
   }
   public String getPhoneNum() {
       return phoneNum;
   }
   public void setPhoneNum(String phoneNum) {
       this.phoneNum = phoneNum;
   }
   public String getfirstName() {
       return this.fname;
   }
   public String getlastName() {
       return this.lname;
   }
   public String getphoneNumber() {
       return this.phoneNum;
   }
}

public class PhoneBook {

   public static void main(String[]args)throws IOException {

       PhoneBook obj = new PhoneBook();

       PhoneContact[]phBook = new PhoneContact[20];

       Scanner in = new Scanner(System.in);
       obj.acceptPhoneContact(phBook,in);
       PrintWriter pw = new PrintWriter("out.txt");

       obj.displayPhoneContacts(phBook,pw);
       pw.close();

   }
   public void acceptPhoneContact(PhoneContact[]phBook, Scanner k) { //void function that takes in the parameters

           //phBook array and the scanner so the user can input the information
           //declaring these variables

           String fname = "";
           String lname = "";
           String contact = "";
           String option = "";
           int count = 0;
          
           System.out.print("Do you have any new contacts to enter(yes)? Enter zzz to exit: ");
           option = k.nextLine();
           while(!(option.contentEquals("zzz")) && count < 20) { //while loop that will continue to ask

               //the user for more contacts if there are not 20 contacts already and if the user does not enter zzz
               System.out.print("Enter first name: ");
               fname = k.nextLine(); //after entering in the name; it stores it in the fname variable
               System.out.print("Enter last name: ");
               lname = k.nextLine();
               System.out.print("Enter phone number: ");
               contact = k.nextLine();
              
               if(phBook[0] != null) { //if this is not empty it will look for a contact

                   if(searchContact(phBook, fname, lname, contact) != null) {//if this is not empty, it'll say the contact exists
                       System.out.println("Contact exists");
                   }else {//otherwise it will add the contact to the phone book
                       phBook[count] = new PhoneContact(fname, lname, contact);
                       count++;
                       if(count >= 20) {
                           System.out.println("You have reached the maximum number of contacts.");
                           break;
                       }
                   }
               }else {//if the phone book array is empty then it will print that the phone book is empty and add the contact
                   if(count==0)
                       System.out.println("Phone book is empty");
                   phBook[count] = new PhoneContact(fname, lname, contact);
                   count++;
               }
               System.out.print("\nDo you have any new contacts to enter(yes)?Enter zzz to exit: ");
               option = k.nextLine();
           }//ends while loop; if the user wants to exit and no longer enter in contacts they will type zzz
           System.out.println("The phone book has " + count + " contacts");
   }
   public int getCurrentContactCount(PhoneContact[]phBook) {
       int numContacts = 0;
       for(int a = 0; a < phBook.length; a++) {
           if(phBook[a] != null) {
               numContacts++;
           }
       }
       return numContacts;
   }
  
   public PhoneContact searchContact(PhoneContact[]phBook, String fname, String lname, String phone) {
       PhoneContact contact= null;
       int n=getCurrentContactCount(phBook);
       for(int a= 0 ; a < n ; a++) {
           if( phBook[a].getfirstName().equalsIgnoreCase(fname) &&
                   phBook[a].getlastName().equalsIgnoreCase(lname) &&
                   phBook[a].getPhoneNum().equalsIgnoreCase(phone)) {//compare lname and phone contact
               System.out.println("Phone book conatct exists");
               contact = phBook[a];
               break;
           }
       }
       return contact;
   }
  
   public void displayPhoneContacts(PhoneContact[]phBook, PrintWriter pw)
           throws IOException{
               int n=getCurrentContactCount(phBook);
               pw.println("Phone Book");
               pw.println("**************************");
               pw.print("First Name\tLast Name\t Contact number");
               for(int a= 0 ; a < n ; a++) {
                   pw.println(phBook[a].getfirstName() +"\t" + phBook[a].getlastName()+"\t" + phBook[a].getphoneNumber());
               }
   }
}

//###########################################################################

OUTPUT
###########

Add a comment
Know the answer?
Add Answer to:
Fix the following null pointer error. import java.util.*; import java.io.*; public class PhoneBook { public static...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I need help running this code. import java.util.*; import java.io.*; public class wordcount2 {     public...

    I need help running this code. import java.util.*; import java.io.*; public class wordcount2 {     public static void main(String[] args) {         if (args.length !=1) {             System.out.println(                                "Usage: java wordcount2 fullfilename");             System.exit(1);         }                 String filename = args[0];               // Create a tree map to hold words as key and count as value         Map<String, Integer> treeMap = new TreeMap<String, Integer>();                 try {             @SuppressWarnings("resource")             Scanner input = new Scanner(new File(filename));...

  • Why does my program generate [] when viewing all guests names? ----------------------------------------------- import java.util.*; public class...

    Why does my program generate [] when viewing all guests names? ----------------------------------------------- import java.util.*; public class Delete extends Info { String name; int Id; int del; public Delete() { } public void display() { Scanner key = new Scanner(System.in); System.out.println("Input Customer Name: "); name = key.nextLine(); System.out.println("Enter ID Number: "); Id = key.nextInt(); System.out.println("Would you like to Delete? Enter 1 for yes or 2 for no. "); del = key.nextInt(); if (del == 1) { int flag = 0; //learned...

  • P1 is below package p6_linkedList; import java.util.*; public class LinkedList { public Node header; public LinkedList()...

    P1 is below package p6_linkedList; import java.util.*; public class LinkedList { public Node header; public LinkedList() { header = null; } public final Node Search(int key) { Node current = header; while (current != null && current.item != key) { current = current.link; } return current; } public final void Append(int newItem) { Node newNode = new Node(newItem); newNode.link = header; header = newNode; } public final Node Remove() { Node x = header; if (header != null) { header...

  • Cant figure out how to fix error Code- import java.io.File; import java.io.IOException; import java.util.*; public class Program8 {    public static void main(String[] args)throws IOException{       ...

    Cant figure out how to fix error Code- import java.io.File; import java.io.IOException; import java.util.*; public class Program8 {    public static void main(String[] args)throws IOException{        File prg8 = new File("program8.txt");        Scanner reader = new Scanner(prg8);        String cName = "";        int cID = 0;        double bill = 0.0;        String email = "";        double nExempt = 0.0;        String tExempt = "";        int x = 0;        int j = 1;        while(reader.hasNextInt()) {            x = reader.nextInt();}        Customers c1 [] = new Customers [x];        for (int...

  • Identify a logical error in the following code and fix it. public class test1 {    ...

    Identify a logical error in the following code and fix it. public class test1 {     public static void main(String[] args){         int total;         float avg;         int a, b, c;         a=10;         b=5;         c=2;         total=a+b+c;         avg=total/3;         System.out.println("Average: "+avg);     } } Answer: Write the output of the program below. import java.util.Scanner; public class test2 { public static void main(String[] arg){ int psid; String name; Scanner input=new Scanner(System.in); System.out.println("Enter your PSID"); psid=input.nextInt(); System.out.println("Enter your...

  • JAVA help Create a class Individual, which has: Instance variables for name and phone number of...

    JAVA help Create a class Individual, which has: Instance variables for name and phone number of individual. Add required constructors, accessor, mutator, toString() , and equals method. Use array to implement a simple phone book , by making an array of objects that stores the name and corresponding phone number. The program should allow searching in phone book for a record based on name, and displaying the record if the record is found. An appropriate message should be displayed if...

  • (How do I remove the STATIC ArrayList from the public class Accounts, and move it to...

    (How do I remove the STATIC ArrayList from the public class Accounts, and move it to the MAIN?) import java.util.ArrayList; import java.util.Scanner; public class Accounts { static ArrayList<String> accounts = new ArrayList<>(); static Scanner scanner = new Scanner(System.in);    public static void main(String[] args) { Scanner scanner = new Scanner(System.in);    int option = 0; do { System.out.println("0->quit\n1->add\n2->overwirte\n3->remove\n4->display"); System.out.println("Enter your option"); option = scanner.nextInt(); if (option == 0) { break; } else if (option == 1) { add(); } else...

  • import java.io.*; import java.util.Scanner; public class CrimeStats { private static final String INPUT_FILE = "seattle-crime-stats-by-1990-census-tract-1996-2007.csv"; private...

    import java.io.*; import java.util.Scanner; public class CrimeStats { private static final String INPUT_FILE = "seattle-crime-stats-by-1990-census-tract-1996-2007.csv"; private static final String OUTPUT_FILE = "crimes.txt"; public static void main(String[] args) { int totalCrimes = 0; // read all the rows from the csv file and add the total count in the totalCrimes variable try { Scanner fileScanner = new Scanner(new File(INPUT_FILE)); String line = fileScanner.nextLine(); // skip first line while (fileScanner.hasNext()) { String[] tokens = fileScanner.nextLine().split(","); if (tokens.length == 4) { totalCrimes +=...

  • import java.util.Scanner; public class TriangleMaker {    public static void main(String[] args) {        //...

    import java.util.Scanner; public class TriangleMaker {    public static void main(String[] args) {        // TODO Auto-generated method stub        System.out.println("Welcome to the Triangle Maker! Enter the size of the triangle.");        Scanner keyboard = new Scanner(System.in);    int size = keyboard.nextInt();    for (int i = 1; i <= size; i++)    {    for (int j = 0; j < i; j++)    {    System.out.print("*");    }    System.out.println();    }    for (int...

  • make this program run import java.util.Scanner; public class PetDemo { public static void main (String []...

    make this program run import java.util.Scanner; public class PetDemo { public static void main (String [] args) { Pet yourPet = new Pet ("Jane Doe"); System.out.println ("My records on your pet are inaccurate."); System.out.println ("Here is what they currently say:"); yourPet.writeOutput (); Scanner keyboard = new Scanner (System.in); System.out.println ("Please enter the correct pet name:"); String correctName = keyboard.nextLine (); yourPet.setName (correctName); System.out.println ("Please enter the correct pet age:"); int correctAge = keyboard.nextInt (); yourPet.setAge (correctAge); System.out.println ("Please enter the...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT