【问题标题】:Java NullPointerException sorting array [closed]Java NullPointerException 排序数组
【发布时间】:2013-02-28 06:42:02
【问题描述】:

我应该能够按姓氏对students 数组进行排序,然后是名字。我的 compareTo 方法适用于它,直到最后一次迭代。然后它抛出一个NullPointerException,我不知道为什么。我已经在我的书和互联网上搜索了将近 12 个小时。我已经尝试了我找到的所有东西,但仍然没有骰子。

这是程序的代码:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ch11pr112;

import java.io.*;
import java.util.Arrays;
/**
 *
 * @author Tytus
 */
public class CH11PR112{

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        // TODO code application logic here
        BufferedReader in = new BufferedReader(new FileReader("src//ch11pr112//Students.txt"));
        Student[] students = new Student[100];
        int i = 0;
        double sum = 0;
        String line = in.readLine();
        while (line != null)
        {
            String[] studentParts = line.split(" ");
            String firstName = studentParts[1];
            String lastName = studentParts[0];
            Double score = Double.parseDouble(studentParts[2]);
            students[i] = new Student(firstName, lastName, score);
            sum += score;
            i++;
            line = in.readLine();
        }
        double average = sum / i;
        double x = i;
        Arrays.sort(students);
        for (i = 0; i < x; i++)
        {
            String studentList = students[i].getLastName() + " " + students[i].getFirstName() + " " + students[i].getScore();
            if (students[i].getScore() < (average - 10))
            {
                System.out.println(studentList + " BELOW AVERAGE");
            }
            else
            {
                System.out.println(studentList);
            }
        }
        System.out.println();
        System.out.println("Average:\t" + average);
    }
}

这是我的 Students.txt 文件中的数据:

Gator Ali 85
Vator Ella 75
Beam John 60
Beam James 95
Class Lastin 55
Steelman Andrea 95
Murach Joel 92
Lowe Doug 82
Murach Mike 93

这是我的 Student.java 文件中的代码:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ch11pr112;

/**
 *
 * @author Tytus
 */
public class Student implements Comparable<Student>{
    private String firstName;
    private String lastName;
    private double score;

    public Student(String firstName, String lastName, double score)
    {
        this.firstName = firstName;
        this.lastName = lastName;
        this.score = score;
    }

    public String getFirstName()
    {
        return firstName;
    }

    public void setFirstName(String firstName)
    {
        this.firstName = firstName;
    }

    public String getLastName()
    {
        return lastName;
    }

    public void setLastName(String lastName)
    {
        this.lastName = lastName;
    }

    public double getScore()
    {
        return score;
    }

    public void setScore(double score)
    {
        this.score = score;
    }

    @Override
    public int compareTo(Student x) {
        int lastNameCompare = this.lastName.compareToIgnoreCase(x.getLastName()); 
        if (this.lastName != null && x.lastName != null)
        {
            if (lastNameCompare == 0)
            {
                int firstNameCompare =     this.firstName.compareToIgnoreCase(x.getFirstName()); 
                if (this.firstName != null && x.firstName != null)
                { 
                    if (firstNameCompare == 0)
                        {
                        return 0;
                    }
                    else if (firstNameCompare > 0)
                    {
                        return 1;
                    }
                    else if (firstNameCompare < 0)
                    {
                        return - 1;
                    }
                }
            }
            else if (lastNameCompare > 0)
            {
                return 1;
            }
            else if (lastNameCompare < 0)
            {
                return - 1;
            }
        }
        return 0;
    }
}

由于某种原因,它在 ComparableTimSort.java 文件的第 232 行 (if (pivot.compareTo(a[mid]) &lt; 0)) 的最后一次迭代期间创建了一个 NullPointerException

问题是如何防止NullPointerException,以及如果lastNamefirstName 变量是null,为什么不应该运行代码时会抛出它。

【问题讨论】:

  • 能否给出错误的stacktrace?
  • 为什么你在for loop之前使用double x = i,为什么不直接使用int x = i?任何具体原因!!!
  • 什么是 ComparableTimSort.java
  • 我可以用intdouble就是我用的那个。使用哪一个并不重要。 ComparableTimSort.java 是一个内置的 Java 文件。我相信它是用 Java 内置的,而不仅仅是 NetBeans(我正在使用的程序)。

标签: java arrays nullpointerexception


【解决方案1】:

我不相信您可以使用 Arrays.sort 对包含空值的数组进行排序,因为最终它会遇到您拥有pivot == null 的情况,因此您尝试进行比较

null.compareTo(Object) < 0

查看Arrays API顶部的警告

如果指定的数组引用为空,则此类中的方法都会抛出 NullPointerException,除非另有说明。

【讨论】:

【解决方案2】:
public static void main(String[] args) throws Exception {
     BufferedReader in = new BufferedReader(new FileReader("src//ch11pr112//Students.txt"));
     String strLine;
     int count = 0;
     while ((strLine = in.readLine()) != null)   {
       count++;
     }
      Student[] students = new Student[count];
     int i = 0;
     double sum = 0;
     in = new BufferedReader(new FileReader("src//ch11pr112//Students.txt"));
     String line = in.readLine();
     System.out.println(line);
     while (line != null)
     {
         String[] studentParts = line.split(" ");
         String firstName = studentParts[1];
         String lastName = studentParts[0];
         Double score = Double.parseDouble(studentParts[2]);
         students[i] = new Student(firstName, lastName, score);
         sum += score;
         i++;
         line = in.readLine();
     }
     double average = sum / i;
     double x = i;
     for(int w=0;w<students.length;w++)
     System.out.println(students[w]);
     Arrays.sort(students);
     for (i = 0; i < x; i++)
     {
         String studentList = students[i].getLastName() + " " + students[i].getFirstName() + " " + students[i].getScore();
         if (students[i].getScore() < (average - 10))
         {
             System.out.println(studentList + " BELOW AVERAGE");
         }
         else
         {
             System.out.println(studentList);
         }
     }
     System.out.println();
     System.out.println("Average:\t" + average);
 }

【讨论】:

  • 我想把它放在一个for 循环中,然后试了一下。唯一的问题是,在sort 完成之前,代码永远不会返回继续循环。
猜你喜欢
  • 2020-05-30
  • 2013-02-16
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 2012-04-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多