如果我尝试编译此代码,我会收到一条错误消息,显示“局部变量 phoneNumber1 是从内部类中访问的;需要声明为 final。
很简单,我该如何解决这个问题,所以它没有这个编译错误?我已经阅读了它的技术规范,我已经完成了教程,但我仍然不知所措。我希望没有人得到报酬来写这个东西。
public class LocalClassExample {
static String regularExpression = "[^0-9]";
public static void validatePhoneNumber(String phoneNumber1, String phoneNumber2) {
int numberLength = 10;
class PhoneNumber {
String formattedPhoneNumber = null;
PhoneNumber(String phoneNumber){
// numberLength = 7;
String currentNumber = phoneNumber.replaceAll(
regularExpression, "");
if (currentNumber.length() == numberLength)
formattedPhoneNumber = currentNumber;
else
formattedPhoneNumber = null;
}
public String getNumber() {
return formattedPhoneNumber;
}
public void printOriginalNumbers() {
System.out.println("Original nubmers are " + phoneNumber1 +
" and " + phoneNumber2);
}
}
PhoneNumber myNumber1 = new PhoneNumber(phoneNumber1);
PhoneNumber myNumber2 = new PhoneNumber(phoneNumber2);
myNumber1.printOriginalNumbers();
if (myNumber1.getNumber() == null)
System.out.println("First number is invalid");
else
System.out.println("First number is " + myNumber1.getNumber());
if (myNumber2.getNumber() == null)
System.out.println("Second number is invalid");
else
System.out.println("Second number is " + myNumber2.getNumber());
}
public static void main(String... args) {
validatePhoneNumber("123-456-7890", "456-7890");
}
}