空指针异常:在 ArrayList 类中使用 .size() 方法时发生。

huangapple go评论77阅读模式
英文:

NullPointerException when using .size() in an Arraylist class

问题

public static void main(String[] args) {

    /* 注意:我有一个名为 "UniversityMember" 的超类,它是 "Instructor" 类的超类 */

    // 声明我需要的东西
    ArrayList<UniversityMember> membersList = new ArrayList<>();
    Scanner read = new Scanner("inputFile.txt"); // 文件包含上述文本

    // 第一步:每次出现 ", " 标志时拆分行
    String[] line = read.nextLine().split(", ");

    // 第二步:将每个值分配给其对应的变量
    String name = line[0];
    String id = line[1];
    long date = Long.parseLong(line[2]);
    Date birthDate = new Date(date);
    char gender = line[3].charAt(0);
    String degree = line[4];
    String specialization = line[5];
    String address = line[6];
    boolean availability = Boolean.parseBoolean(line[7]);

    // 检查是否已经注册了该 ID
    for (int i = 0; i < membersList.size(); i++) { // 错误发生处
        if (membersList.get(i) == null) {
            break;
        }

        if (membersList.get(i).id.equals(id)) {
            System.out.println("该讲师已经注册,ID 已在系统中找到。");
            System.exit(0);
        }
    }

    // 添加并创建构造函数的新对象
    membersList.add(new Instructor(name, id, birthDate, gender, degree, specialization, address, availability));
    System.out.println("讲师已成功添加。");

} // 结束主函数
英文:

currently, I'm doing an assignment that deals with the ArrayList class.
at some point, I need to check of the id of the instructor and make sure that the instructor is not added twice to the ArrayList, so I made a for loop to go through all the id that has been registered and get the id and check if it exists already

the problem is when I use the method " .size()" in the loop, the JVM throws NullPointerException
and I don't know why.

==========================================================================

what I need to read is this:

\\name - id - dateOfBirth - gender - degree - speciality - city - availability

Amanda Smith, 102020, 320101200000, M, PhD, Software Engineering, NewYork, true

=======================================================================

this is the code:

public static void main(String[] args) {
/* NOTE: I HAVE A CLASS CALLED &quot;UniversityMember&quot; THAT IS A SUPERCLASS FOR &quot;Instructor&quot; CLASS */
//declare what I need   
ArrayList&lt;UniversityMember&gt; membersList;
Scanner read = new Scanner(&quot;inputFile.txt&quot;);//the file contains the text above
//First: Split the line everytime the sign &quot;, &quot; shows
String[] line = read.nextLine().split(&quot;, &quot;);
//Second: Assign each valuse to its correspondeding variable
String name = line[0];
String id = line[1];
long date = Long.parseLong(line[2]);
Date birthDate = new Date(date);
char gender = line[3].charAt(0);
String degree = line[4];
String specialization = line[5];
String address = line[6];
boolean availability = Boolean.parseBoolean(line[7]);
//check if the Id is registered already
for (int i = 0; i &lt; membersList.size(); i++) { //ERROR OCCURE
if (membersList.get(i) == null) {
break;
}
if (membersList.get(i).id.equals(id)) {
System.out.println(&quot;The instructor is registered already, the ID is found in the system.&quot;);
System.exit(0);
}
}
//add and make a new object for the constructor
membersList.add(new Instructor(name, id, birthDate, gender, degree, specialization, address, availability));
System.out.println(&quot;The instructor is successfully added.&quot;);
}//end main

答案1

得分: 1

问题在于当您在其上调用 .size() 时,membersList 不存在。

而不是

ArrayList<UniversityMember> membersList;

您需要初始化它

ArrayList<UniversityMember> membersList = new ArrayList<UniversityMember>();
英文:

The problem is membersList doesn't exist when you call .size() on it

instead of

ArrayList&lt;UniversityMember&gt; membersList;

you need to initialize it

ArrayList&lt;UniversityMember&gt; membersList = new ArrayList&lt;UniversityMember&gt;();

答案2

得分: 1

你需要初始化 ArrayList。就像这样初始化 ArrayList membersList = new ArrayList<方法名称>();。在此之后,第一次调用 size() 会返回 0 而不是 null。记住,在 Java 中,所有的数据结构都必须进行初始化。

英文:

You need to initialize the ArrayList.
Like that ArrayList<UniversityMember> membersList = new ArrayList<Method name>();
After that, in the first size() returns 0 and not null. Remember all data structure must be initialize in java.

答案3

得分: 0

你还没有向membersList中添加任何内容,然后却要求获取一个没有内容的东西的大小。以下是正在发生的情况示例:

String str;

for(int i = 0; i < str.length(); i++){
    System.out.println("hey");
}

另外,你需要像这样声明ArrayList:

ArrayList<Method name> membersList = new ArrayList<Method name>();

还要别忘了导入ArrayList类:

import java.util.ArrayList;
英文:

You haven't added anything to the membersList then asking for the size for something that has nothing in it.
Example of whats going on

String str;
for(int i = 0; i &lt; str.length(); i++){
System.out.println(&quot;hey&quot;);
}

also you need to declare the array list like this

ArrayList&lt;Method name&gt; membersList = new ArrayList&lt;Method name&gt;();

also don't forget to import the ArrayList class

import java.util.ArrayList;

答案4

得分: 0

nvm我发现我没有初始化我的数组 ω 
我会保留这个问题以便其他人注意

==================================================

修复后的代码
```java
    public static void main(String[] args) {

    /* 注意:我有一个名为“UniversityMember”的类,它是“Instructor”类的超类 */

    //声明我需要的东西   
    ArrayList<UniversityMember> membersList;
    Scanner read = new Scanner("inputFile.txt");//文件包含上面的文本

    /* ===== 修复错误 ======*/
     membersList = new ArrayList();

    //首先:每次出现“, ”标记时拆分行
    String[] line = read.nextLine().split(", ");

    //其次:将每个值分配给其对应的变量
    String name = line[0];
    String id = line[1];
    long date = Long.parseLong(line[2]);
    Date birthDate = new Date(date);
    char gender = line[3].charAt(0);
    String degree = line[4];
    String specialization = line[5];
    String address = line[6];
    boolean availability = Boolean.parseBoolean(line[7]);

    //检查Id是否已注册
    for (int i = 0; i < membersList.size(); i++) { 
        if (membersList.get(i) == null) {
            break;
        }

        if (membersList.get(i).id.equals(id)) {
            System.out.println("该讲师已经注册,系统中找到了该ID。");
            System.exit(0);
        }
    }

    //添加并为构造函数创建一个新对象
    membersList.add(new Instructor(name, id, birthDate, gender, degree, specialization, address, availability));
    System.out.println("成功添加了该讲师。");

}//end main
英文:

nvm I figured out that I haven't initialized my array ( ╥ω╥ )
I'll keep the question for others to be carefull

==================================================

The code after fixing it:

    public static void main(String[] args) {
/* NOTE: I HAVE A CLASS CALLED &quot;UniversityMember&quot; THAT IS A SUPERCLASS FOR &quot;Instructor&quot; CLASS */
//declare what I need   
ArrayList&lt;UniversityMember&gt; membersList;
Scanner read = new Scanner(&quot;inputFile.txt&quot;);//the file contains the text above
/* ===== FIXING THE ERROR ======*/
membersList = new ArrayList();
//First: Split the line everytime the sign &quot;, &quot; shows
String[] line = read.nextLine().split(&quot;, &quot;);
//Second: Assign each valuse to its correspondeding variable
String name = line[0];
String id = line[1];
long date = Long.parseLong(line[2]);
Date birthDate = new Date(date);
char gender = line[3].charAt(0);
String degree = line[4];
String specialization = line[5];
String address = line[6];
boolean availability = Boolean.parseBoolean(line[7]);
//check if the Id is registered already
for (int i = 0; i &lt; membersList.size(); i++) { 
if (membersList.get(i) == null) {
break;
}
if (membersList.get(i).id.equals(id)) {
System.out.println(&quot;The instructor is registered already, the ID is found in the system.&quot;);
System.exit(0);
}
}
//add and make a new object for the constructor
membersList.add(new Instructor(name, id, birthDate, gender, degree, specialization, address, availability));
System.out.println(&quot;The instructor is successfully added.&quot;);
}//end main

huangapple
  • 本文由 发表于 2020年4月4日 08:22:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/61022292.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定