gpt4 book ai didi

java - 使用对象数组时出现 NullPointerException

转载 作者:行者123 更新时间:2023-12-01 22:34:57 25 4
gpt4 key购买 nike

我在这个程序中收到NullPointerException。我相信声明对象数组时存在一些问题。

import java.util.Scanner;

class One
{
public static void main(String args[])
{
Scanner key = new Scanner(System.in);
two[] obj = new two[3];

for (int i = 0; i < 3; i++) {
obj[i].roll = key.nextInt();
obj[i].name = key.nextLine();
obj[i].grade = key.nextLine();
}

for (int i = 0; i < 3; i++) {
System.out.println(obj[i].roll + " " + obj[i].name + " " + obj[i].grade);
}
}
}

class Two
{
int roll;
String name, grade;
}

最佳答案

您忘记初始化数组中的对象。如果没有此初始化,obj[i] 将包含空引用。

two[] obj=new two[3];
for(int i=0;i<3;i++)
{
obj[i] = new two();
obj[i].roll=key.nextInt();
obj[i].name=key.nextLine();
obj[i].grade=key.nextLine();
}

关于java - 使用对象数组时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26994115/

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