Java 数组构造函数抛出NullPointerException
注: 我已经准备好了文章“什么是NPE以及如何修复它” 但是,本文并没有针对特定的数组进行讨论,我认为 嫌疑犯是我代码中的错误源 这是一个从字符串(必须使用charAt()和getNumericValue)将UPC代码(12位)构造为int[]数组的程序。但是,它会按原样在构造函数中抛出NullPointerExceptionJava 数组构造函数抛出NullPointerException,java,arrays,nullpointerexception,Java,Arrays,Nullpointerexception,注: 我已经准备好了文章“什么是NPE以及如何修复它” 但是,本文并没有针对特定的数组进行讨论,我认为 嫌疑犯是我代码中的错误源 这是一个从字符串(必须使用charAt()和getNumericValue)将UPC代码(12位)构造为int[]数组的程序。但是,它会按原样在构造函数中抛出NullPointerException public class UPC { private int[] code; public UPC(String upc) { int
public class UPC {
private int[] code;
public UPC(String upc) {
int[] newUPC = new int[12];
char currentChar;
for (int i=0; i<upc.length();i++) {
currentChar = upc.charAt(i);
code[i] = Character.getNumericValue(currentChar);
}
}
public static void main (String[] args){
// call static method to display instructions (already written below)
displayInstructions();
// While the string entered is not the right length (12 chars),
// tell the user to enter a valid 12-digit code.
Scanner scn = new Scanner(System.in);
// Declare string and read from keyboard using Scanner object
// instantiated above
String str = scn.nextLine();
if (str.length()!=12) {
System.out.println("Please Enter a Valid 12-Digit Code");
} else {
System.out.println("You are good");
}
// Create a new UPC object, passing in the valid string just
// entered.
UPC ourUPC = new UPC(str);
公共类UPC{
私有int[]码;
公共UPC(字符串UPC){
int[]newUPC=新int[12];
字符当前字符;
对于(int i=0;i
为空。您必须创建它:
private int[] code = new int[12];
或更动态:
public UPC(String upc) {
code = new int[upc.length()];
}
在使用此数组code
之前,应按如下方式初始化它:
private int[] code = new int[12];
private int[] code;
public UPC(String upc) {
code = new int[12];
或者像这样在构造函数中:
private int[] code = new int[12];
private int[] code;
public UPC(String upc) {
code = new int[12];
您没有声明code[]您没有初始化code
您的code
数组未初始化。您应该执行int[]code=newcode[12];
或类似操作。或者您可能打算在循环中执行newUPC[i]
。@Phil Chen可以随意接受给定的答案之一。