该方法应返回一个已排序的数组,但为什么我会得到NullPointerException?

时间:2015-02-15 02:12:41

标签: java

最初我的文本文件有行:

12
Steve Jobs 9 final 91
Bill Gates 6 midterm 90
James Gosling 3 midterm 100
James Gosling 3 final 100
Dennis Ritchie 5 midterm 94
Steve Jobs 9 midterm 95
Dennis Ritchie 5 final 100
Jeff Dean 7 midterm 100
Bill Gates 6 final 96
Jeff Dean 7 final 100
Sergey Brin 27 final 97
Sergey Brin 22 midterm 99

方法public static Exam [] readAllExams(Scanner s)创建并返回一个对象数组。 请注意字符串的第一个字母' final'和期中'转换为char。因此,当我运行readAllExams()时,结果是:

Steve Jobs 9 f 91
Bill Gates 6 m 90
James Gosling 3 m 100
James Gosling 3 f 100
Dennis Ritchie 5 m 94
Steve Jobs 9 m 95
Dennis Ritchie 5 f 100
Jeff Dean 7 m 100
Bill Gates 6 f 96
Jeff Dean 7 f 100
Sergey Brin 27 f 97
Sergey Brin 22 m 98

但是,当我运行公共静态考试[] collat​​eExams(考试[]考试)时,它会在此行中为我提供NullPointerException:if(exams[i].getExamType()=='m')。 smb可以解释/帮助我吗? 请注意,getExamType()会返回一个字符。

 import java.io.*;
    import java.util.*;

class P2 {

    public static void main(String [] args) throws FileNotFoundException
    {

    Scanner data = new Scanner(new File("Exam.txt"));
    Exam[] readObjects = readAllExams(data);
    Exam[] collateObjects = collateExams(readObjects);

    System.out.println("1) Initially the list of exams of students is: ");
    System.out.println();
    for(int i = 0; i < readObjects.length; i++)
    {
        System.out.println(readObjects[i]);
    }
    System.out.println("Sorted list: ");
    for (int i = 0; i < collateObjects.length; i++)
    {
        System.out.println(collateObjects[i]);
    }
}



    public static Exam[] readAllExams(Scanner s) throws ArrayIndexOutOfBoundsException
    {

        String firstName = "";
        String lastName = "";
        int ID = 0;
        String examType = "";
        char examTypeCasted;
        int score = 0;

        int index = 0;

        Exam[] object = new Exam[s.nextInt()];

        while(s.hasNext())
        {
            //Returns firtsName and lastName 
            firstName = s.next();
            lastName = s.next();

            //Returns ID number
            if(s.hasNextInt())
            {
                ID = s.nextInt();
            }
            else 
                s.next();

            //Returns examType which is 'M' or 'F'
            examType = s.next();
            examTypeCasted = examType.charAt(0);

            if(s.hasNextInt())
            {
                score = s.nextInt();
            }
            //Exam[] object = new Exam[s.nextInt()];

            object[index] = new Exam(firstName, lastName, ID, examTypeCasted, score);
            //System.out.println();
            index++;
        }
        readExam(s);
        return object;


    }

    public static Exam readExam(Scanner s)
    {
        String firstName = "";
        String lastName = "";
        int ID = 0;
        String examType = "";
        char examTypeCasted = 0;
        int score = 0;

        while (s.hasNext())
        {
            //Returns firtsName and lastName 
            firstName = s.next();
            lastName = s.next();

            //Returns ID number
            if(s.hasNextInt())
            {
                ID = s.nextInt();
            }
            //Returns examType which is 'M' or 'F'
            examType = s.next();
            examTypeCasted = examType.charAt(0);

            if(s.hasNextInt())
            {
                score = s.nextInt();
            }

        }
        Exam temp = new Exam(firstName, lastName, ID, examTypeCasted, score);
        return temp;
    }

    public static Exam[] collateExams(Exam[] exams)
    {
        Exam [] r = new Exam[exams.length];
        r = exams; 
        int [] position = new int[exams.length];


        for(int i = 0;i < position.length;i++)
            position[i]=-1;
        int index = 0;


        for(int i = 0; i < exams.length; i++)
        {

           if(exams[i].getExamType()=='m')
           {
               if(position[exams[i].getID()]==-1)
               {
                   r[index*2]=new Exam(r[i].getFirstName(), r[i].getLastName(), r[i].getID(), r[i].getExamType(), r[i].getScore());
                   position[exams[i].getID()] = 2*index;

               }
               else r[2*position[exams[i].getID()] - 1]=new Exam(r[i].getFirstName(), r[i].getLastName(), r[i].getID(), r[i].getExamType(), r[i].getScore());
           }
           else
           {
               if(position[exams[i].getID()]==-1)
               {
                   r[index*2+1] = new Exam(r[i].getFirstName(), r[i].getLastName(), r[i].getID(), r[i].getExamType(), r[i].getScore());
                   position[exams[i].getID()] = 2*index+1;
               }

              else    r[2*position[exams[i].getID()]+1]=new Exam(r[i].getFirstName(), r[i].getLastName(), r[i].getID(), r[i].getExamType(), r[i].getScore());
           }
           index++;

        }

        return r;
        /*Exam [] r = new Exam[100];
        r = exams;
        int[] position = new int[100];
        int index = 0;


        for(int i = 0; i < exams.length; i++)
        {
            if(r[i].getExamType() == 'm')
            {   

                r[index] = new Exam(r[index].getFirstName(), r[index].getLastName(),
                                  r[index].getID(), r[index].getExamType(), r[index].getScore());

                position[index] = r[index].getID();
                index+=2;

                /*if((r[index+1].getExamType() == 'F') && (position[index+1] == r[i].getID()))
                {
                    r[index+1] = new Exam(r[index].getFirstName(), r[index].getLastName(),
                              r[index].getID(), r[index].getExamType(), r[index].getScore());
                }
                /*if(position[i].getID() == r[i].getID())
                    r[i] = new Exam(r[i].getFirstName(), r[i].getLastName(),
                              r[i].getID(), r[i].getExamType(), r[i].getScore()); 



            }
            else if((r[index+1].getExamType() == 'f') && position[index] == r[i].getID())
            {
                r[index + 1] = new Exam(r[index].getFirstName(), r[index].getLastName(),
                          r[index].getID(), r[index].getExamType(), r[index].getScore());
            }

        }

        return r;*/



    }
}

1 个答案:

答案 0 :(得分:1)

当我运行你的代码时,我没有获得空指针异常,但是当你执行r * 2时,索引超出范围异常。这不会起作用,因为你为你的数组分配12个点,迭代12个项目,然后告诉它在迭代时转到n * 2。它迅速超越了界限。还有一些其他问题将ID设置为数组索引等。我为您清理了一些代码并遵循了您的意图(分配两个位置,假设检查数量包括两个ID,一个M和一个F)。请注意,您的文本文件还包含Sergey Brin的ID中的错误,该错误打破了这一假设。这可能不是你的最终产品,但它得到你在那里工作的东西:

public static void main(String [] args) throws FileNotFoundException
{        
    Scanner data = new Scanner(new File("exams.txt"));
    Exam[] readObjects = readAllExams(data);

    System.out.println("1) Initially the list of exams of students is: ");
    System.out.println();
    for(int i = 0; i < readObjects.length; i++)
    {
        System.out.println(readObjects[i]);
    }

    Exam[] collateObjects = collateExams(readObjects);

    System.out.println("Sorted list: ");
    for (int i = 0; i < collateObjects.length; i++)
    {
        System.out.println(collateObjects[i]);
    }
}

public static Exam[] readAllExams(Scanner s) throws ArrayIndexOutOfBoundsException
{

    int index = 0;
    Exam[] object = new Exam[s.nextInt()];

    while(s.hasNext())
    {
        object[index] = readExam(s);
        index++;
    }

    return object;
}

public static Exam readExam(Scanner s)
{
    String firstName = "";
    String lastName = "";
    int ID = 0;
    String examType = "";
    char examTypeCasted = 0;
    int score = 0;

    //Returns firtsName and lastName 
    firstName = s.next();
    lastName = s.next();

    //Returns ID number
    if(s.hasNextInt())
    {
        ID = s.nextInt();
    }
    //Returns examType which is 'M' or 'F'
    examType = s.next();
    examTypeCasted = examType.charAt(0);

    if(s.hasNextInt())
    {
        score = s.nextInt();
    }

    return new Exam(firstName, lastName, ID, examTypeCasted, score);
}

public static Exam[] collateExams(Exam[] exams)
{
    Exam [] r = new Exam[exams.length];
    System.arraycopy(exams, 0, r, 0, exams.length); 

    int [] position = new int[exams.length];


    for(int i = 0;i < position.length;i++)
        position[i]=-1;

    for(int i = 0; i < exams.length; i++)
    {
       int nextPos = determineNextPosition(position, exams[i]);
       r[nextPos] = new Exam(exams[i].getFirstName(), exams[i].getLastName(), exams[i].getID(), exams[i].getExamType(), exams[i].getScore());
    }

    return r;
}

private static int determineNextPosition(int[] posArray, Exam exam)
{
    int position = -1;
    int id = exam.getID();

    // see if there is a spot for the ID already
    for (int i = 0; i < posArray.length; i++)
    {
        if (posArray[i] == id)
        {
            position = i;
            break;
        }
    }

    if (position < 0)
    {
        // if a spot wasnt found, make one
        for (int i = 0; i < posArray.length; i+=2)
        {
            if (posArray[i] == -1)
            {
                posArray[i] = id;
                posArray[i+1] = id;
                position = i;
                break;
            }
        }
    }

    if (position < 0) throw new RuntimeException("Something went really wrong");

    if (exam.getExamType() == 'm')
    {
        return position;
    }
    else
    {
        return position + 1;
    }               
}