我正在为我正在学习的计算机科学类(class)做作业,我试图在一行中声明 3 个字符串数组,但它一直给我这个错误消息
java.lang.NullPointerException
我稍微搞了一下,然后通过更改解决了问题
public static String[] offence,name,date = new String[8];
到
public static String[] offence,name = new String[8];
public static String[] date = new String[8];
为什么只有当我这样做时它才起作用?
PS,我是新人,所以对我宽容一些。
package pDatabaseApp;
import java.io.*;
public class PDatabaseMenu {
public static String[] offence,name = new String[8];
public static String[] date = new String[8];
public static void main(String[] args) throws IOException {
String line;
BufferedReader in;
in = new BufferedReader(new InputStreamReader(System.in));
boolean finnish = false, reenter = false;
while(finnish == false) {
int i;
for(i = 0; i <= 7; i++) {
System.out.println("enter a name");
name[i] = in.readLine();
System.out.println("enter a day");
String day = in.readLine();
System.out.println("enter a month");
String month = in.readLine();
System.out.println("enter a year");
String year = in.readLine();
date[i] = day + "/" + month + "/" + year;
String offenceEnter[] = new String[3];
String offenceType[] = {"Assault","Arson","Theft"};
int l;
for(l = 0; l <= 2; l++) {
System.out.println("is there offence " + offenceType[l]);
offenceEnter[l] = in.readLine();
if(offenceEnter[l] == "yes") {
offence[i] = offenceType[l];
}
}
}
}
in.close();
}
}
最佳答案
记住代码,
public static String[] offence,name,date = new String[8];
只会初始化日期。因此,其他变量保持未初始化状态。结果你得到了java.lang.NullPointerException
。
你需要类似的东西
public static String[] offence= new String[8],name= new String[8],date = new String[8];
关于java - 一行中不能声明超过 2 个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51883124/