java - 局部变量可能尚未初始化构造函数/方法

标签 java variables methods constructor local

代码还远未完成,但我基本上一直停留在这个问题上,直到我可以进一步前进。继续获取本地变量可能尚未在他们的电话上初始化。如果我将构造函数移动到 try catch,我会在 try catch 上收到错误,如果我保持原样,我会在 yourPhone.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;
    }

}

最佳答案

简单修复:将引用初始化为 null:

CustomerTelephone theirPhone = null;

更好的修复:初始化变量并将对该变量的引用移至 try block 中。因此,如果在 try block 中引发异常,则可以避免后续的 NullPointer 异常。

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

关于java - 局部变量可能尚未初始化构造函数/方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26367288/

相关文章:

java - 即使我关闭 RS,结果集资源也会泄漏?

java - 先前有效的功能的链接不满意

javascript - 清除区间和变量: clearinterval fails

variables - NGINX - 在 proxy_pass 中使用变量会破坏路由

go - Golang 中的未定义错误

function - Go中的函数和方法有什么区别?

java - 将文件名与 id 进行匹配

java - 检查整数中的降序数字

variables - Mathematica- 在给定随机变量和设置方程时求解

ruby-on-rails - Ruby on Rails - 除非多个条件