我明白了
线程中的异常 "主" java.lang.NullPointerException at SwedishPersonalNumber。(ScanPersonalNumber.java:5)在 ScanPersonalNumber.main(ScanPersonalNumber.java:54)
我的斗争是返回getYearBorn。但我不知道我是什么 做错了。我可以用字符串解决getYearBorn,但它是一个练习 我需要它是int。
import java.util.Scanner;
class SwedishPersonalNumber {
String personalNumber;
String personalNumberBorn = personalNumber.substring(0, 4);
String female = "Female";
String male = "Male";
// boolean isValid = true;
int yearBorn = Integer.parseInt(personalNumberBorn);
int getYearBorn() {
return yearBorn;
}
String getGender() {
if (personalNumber.charAt(10)%2 == 0) {
return female;
}
else
return male;
}
/*
boolean isValid() {}
*/
}
public class ScanPersonalNumber {
public static void main (String[] args) {
String scanPersonalNumber;
Scanner kb = new Scanner(System.in);
System.out.println("Enter your personalnumber likes this: 196112033581 ");
System.out.println("Now please enter your personalnumber");
scanPersonalNumber = kb.nextLine();
System.out.println("Your personalnumber is: "+ scanPersonalNumber);
SwedishPersonalNumber myPersonalNumber = new SwedishPersonalNumber();
myPersonalNumber.personalNumber = scanPersonalNumber;
kb.close();
System.out.println("Your birthyear is: "+ myPersonalNumber.getYearBorn());
System.out.println("You are: "+ myPersonalNumber.getGender());
}
}
答案 0 :(得分:0)
问题是你正在尝试将personalNumberBorn初始化为早期,逻辑上你正在做的事情是正确的,当你说personalNumberBorn应该是personalNumber的子字符串但是如果你试图从编译器的角度来看它这就是将要发生的事情:
String personalNumber; // 1) The compiler creates a empty (null) string.
String personalNumberBorn = personalNumber.substring(0, 4); // 2) The compiler tries to take a substring of personalNumber which we know is empty (null)
解决这个问题的标准方法是编写我们自己的构造函数,你的代码看起来像这样:
//...
String personalNumber;
String personalNumberBorn;
String female = "Female";
String male = "Male";
// boolean isValid = true;
int yearBorn;
public SwedishPersonalNumber(String personalNr) { //Constructor
personalNumber = personalNr;
personalNumberBorn = personalNumber.substring(0, 4);
yearBorn = Integer.parseInt(personalNumberBorn);
}
//...
而不是像这样打电话:
SwedishPersonalNumber myPersonalNumber = new SwedishPersonalNumber();
你是这样做的:
SwedishPersonalNumber myPersonalNumber = new SwedishPersonalNumber(scanPersonalNumber);