2013-02-28 3 views
0

students 배열을 성, 그 다음 이름 순으로 정렬 할 수 있어야합니다. 마지막으로 반복 할 때까지 내 compareTo 메서드가 작동합니다. 그런 다음 NullPointerException을 던지고 나는 그 이유를 모릅니다. 나는 나의 책과 인터넷을 거의 12 시간 동안 수색 해왔다. 나는 내가 찾은 모든 것을 시도했지만 여전히 주사위를 사용하지 않았다. 여기 Java NullPointerException 정렬 배열

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; 

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 파일의 데이터입니다 :

여기

는 프로그램의 코드입니다
/* 
* 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; 
    } 
} 

라인 232의 마지막 반복 중에 NullPointerException이 생성됩니다 (if (pivot.compareTo(a[mid]) < 0))은 ComparableTimSort.java입니다.

문제는 NullPointerException 및 이유 코드 중 하나 lastName 또는 firstName 변수 null을 경우 실행되는 가정하지 않는 경우가 발생되는 것을 방지하는 방법입니다.

난 당신이 비교를 시도 있도록, 배열은 결국 당신이 pivot == null이 상황에 실행 정확하게 이유, 널 (null)을 포함하는 정렬 Arrays.sort에 사용할 수 있습니다 생각하지 않는다
+0

오류의 스택 추적을 제공 할 수 있습니까? –

+0

'for loop' 바로 전에'double x = i'를 사용하는 이유는 간단히'int x = i'가 아닌가? 어떤 특별한 이유 !!! –

+1

무엇이 ComparableTimSort.java입니까 –

답변

4

null.compareTo(Object) < 0 

지정된 배열 참조는 명시된 경우를 제외하고는, 널 (null) 인 경우 모두 NullPointerException이 던져이 클래스 Arrays API

방법의 상단에 경고가 표시.

+3

+1 문제는'Student [100]'이며, 기본적으로'null '로 채워진 여분의 항목을 남겨 둡니다. OP는 오버로드 된 버전 ['Arrays.sort (data, fromIndex, toIndex)']을 사용해야합니다.] (http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#sort%28java .lang.Object % 5B % 5D, % 20int, % 20int % 29). – mellamokb

+1

예, 그 중 하나 또는 [비교자를 인수로 사용하는 정렬 방법] (http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#sort (T [], % 20java.util.Comparator)).이 경우 null 값은 [Comparator] (http://docs.oracle.com/javase/6/docs/api/java/util/Comparator)에서 효과적으로 처리 할 수 ​​있습니다. .html). – femtoRgon

+0

불행히도 지시문에는 'Comparable'을 사용해야한다고 나와 있습니다. –

1
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); 
} 
+0

나는 그것을 for 루프에 넣을 생각을하고 그것을 시도했다. 유일한 문제는 'sort'가 완료 될 때까지 루프가 계속 돌아 가지 않는다는 것입니다. –