Yitzak Hernandez
Yitzak Hernandez

Reputation: 357

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;
    }

}

Upvotes: 1

Views: 1427

Answers (3)

EJK
EJK

Reputation: 12534

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 {
...
}

Upvotes: 2

Yuriy Nakonechnyy
Yuriy Nakonechnyy

Reputation: 3842

Well, it makes sense: compiler tells you that if InvalidTelephoneException is thrown in try block, then execution goes to catch block, System.out.println prints error message to console and goes further to theirPhone.getAreaCode(phoneNumber) BUT at this point theirPhone is null so NullPointerException will be thrown.

I would recommend to add return; statement after Systen.out.println line so that program terminates in case of invalid phone number format.

Hope this helps...

Upvotes: 1

Tuy
Tuy

Reputation: 33

The problem seems to be that theirPhone is not necessarily initialized in the main method in the try block that follows it (the compiler will assume that there is a chance of failure at any point in the block). Try giving the variable a default value or null when it is declared.

Upvotes: 0

Related Questions