gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:43:10 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com