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