Search code examples
javavariablesmethodsconstructorlocal

The local variable may not have been initialized constructor/method


Code is nowhere near done but I'm basically stuck at this until I can move any further. Keep getting a local variable may not have been initialized on theirPhone.. If I move the constructor passed the try catch I get an error on the try catch, if I leave it the way it is I get the error at theirPhone.getAreaCode(phoneNumber); any help?

import java.util.Scanner;

public class CustomerTelephone {

    public static void main(String[] args) {
        CustomerTelephone theirPhone;
        String phoneNumber = "407 407 4074";

        try {
            theirPhone = new CustomerTelephone(phoneNumber);
        } catch (InvalidTelephoneException ite) {
            System.out.println("Invalid telephone number format.");
        }

        theirPhone.getAreaCode(phoneNumber);

    }

    public CustomerTelephone(String telephone) throws InvalidTelephoneException {
        if (telephone.length() != 12) {
            throw new InvalidTelephoneException(
                "The phone number was entered incorrectly.");
        }
    }

    public String getAreaCode(String phoneNumber) {
        String goBack;
        String[] teleArray = phoneNumber.split("(?!^)");
        goBack = teleArray[0 - 2];

        return goBack;
    }

    public String getExchange(String phoneNumber) {
        String goBack = null;

        return goBack;
    }

    public String getLocalNumber(String phoneNumber) {
        String goBack = null;

        return goBack;
    }

}

Solution

  • Simple fix: Initialize the reference to null:

    CustomerTelephone theirPhone = null;
    

    Better fix: Initialize the variable and move the reference to that variable into the try block. Thus if an exception is thrown in your try block, then you avoid a subsequent NullPointer exception.

    CustomerTelephone theirPhone = null;
     ...
    try {
        theirPhone = new CustomerTelephone(phoneNumber);
        theirPhone.getAreaCode(phoneNumber);
    } catch {
    ...
    }