Java 局部变量可能尚未初始化构造函数/方法
代码还远没有完成,但我基本上被困在这一点上,直到我可以进一步。保持获取局部变量可能尚未在电话上初始化。。如果我移动通过try-catch的构造函数,我会在try-catch上得到一个错误,如果我保持原样,我会在他们的phone.getAreaCode(phoneNumber)上得到错误;有什么帮助吗Java 局部变量可能尚未初始化构造函数/方法,java,variables,methods,constructor,local,Java,Variables,Methods,Constructor,Local,代码还远没有完成,但我基本上被困在这一点上,直到我可以进一步。保持获取局部变量可能尚未在电话上初始化。。如果我移动通过try-catch的构造函数,我会在try-catch上得到一个错误,如果我保持原样,我会在他们的phone.getAreaCode(phoneNumber)上得到错误;有什么帮助吗 import java.util.Scanner; public class CustomerTelephone { public static void main(String[] a
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块中。因此,如果在try块中抛出一个异常,则可以避免后续的null指针异常
CustomerTelephone theirPhone = null;
...
try {
theirPhone = new CustomerTelephone(phoneNumber);
theirPhone.getAreaCode(phoneNumber);
} catch {
...
}
问题似乎是,
theirPhone
不一定在紧随其后的try块中的main方法中初始化(编译器将假定块中的任何点都有失败的可能性)。在声明变量时,尝试为其指定一个默认值或null。这很有意义:编译器告诉您,如果InvalidTelephoneException
被抛出Try
块,则执行转到catch
块,System.out.println
将错误消息打印到控制台,并进一步转到theirPhone.getAreaCode(phoneNumber)
但此时theirPhone
为null
因此将抛出NullPointerException
我建议添加return在Systen.out.println
行之后的code>语句,以便在电话号码格式无效的情况下程序终止
希望这有帮助…这会起作用,但无论如何都会导致NullPointerException
如果InvalidTelephoneException
被抛出try
block:)现在我该如何捕捉NullPointerException?NPE的公平点。我已经更新了我的答案来解释这一点。