【问题标题】:The local variable may not have been initialized constructor/method局部变量可能尚未初始化构造函数/方法
【发布时间】:2014-12-09 15:06:17
【问题描述】:

代码还远未完成,但在我可以继续前进之前,我基本上被困在这上面。继续获取局部变量可能尚未在 theirPhone 上初始化。如果我移动构造函数通过 try catch,我会在 try catch 上收到错误,如果我保持原样,我会在 theirPhone.getAreaCode(phoneNumber );有什么帮助吗?

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

}

【问题讨论】:

    标签: java variables methods constructor local


    【解决方案1】:

    简单修复:初始化对 null 的引用:

    CustomerTelephone theirPhone = null;
    

    更好的解决方法:初始化变量并将对该变量的引用移动到 try 块中。因此,在您的 try 块中引发了异常,然后您避免了后续的 NullPointer 异常。

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

    【讨论】:

    • 这会起作用,但如果InvalidTelephoneException 被抛出try 块,无论如何都会导致NullPointerException :)
    • 现在我将如何捕获 NullPointerException?
    • 关于 NPE 的公平点。我已经更新了我的答案来解决这个问题。
    【解决方案2】:

    嗯,这是有道理的:编译器告诉你,如果InvalidTelephoneException 被抛出到try 块中,那么执行将转到catch 块,System.out.println 将错误消息打印到控制台并进一步转到theirPhone.getAreaCode(phoneNumber) BUT此时theirPhonenull 所以NullPointerException 将被抛出。

    我建议在Systen.out.println 行之后添加return; 语句,以便在电话号码格式无效的情况下终止程序。

    希望这会有所帮助...

    【讨论】:

      【解决方案3】:

      问题似乎在于 theirPhone 不一定在其后的 try 块中的 main 方法中初始化(编译器会假设该块中的任何点都有失败的可能性)。尝试在声明变量时给变量一个默认值或 null。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多