Comparable and Arrays.Sort

2

I'm having difficulty using the comparable interface, I should do the increasing comparison of pilots according to their score (class PilotoEquipe ), and then in class CorridaX1 , I need to use Arrays.sort to organize the array of pilots. When I run Arrays.sort I get the following error:

  

Exception in thread "main" java.lang.NullPointerException at   ComparableTimSort.java:316     at java.util.ComparableTimSort.sort (ComparableTimSort.java:184) at   java.util.Arrays.sort (Arrays.java:1246) at   LeonardoBruksch.CorridaX1.orderna (CorridaX1.java:41) at   LeonardoBruksch.ControleFederacao.main (ControlFederacao.java:35) Java   Result: 1

Pilot Class Team:

public class PilotoEquipe implements PilotoEquipeInterface, Comparable<PilotoEquipe>{
    protected String nome;
    protected String equipe;
    protected double pontos;

    public PilotoEquipe(String nome, String equipe, double pontos){
        this.nome = nome;
        this.equipe = equipe;
        this.pontos = pontos;
    }

    @Override
    public String getNome() {
        return nome;
    }

    @Override
    public void setNome(String nome) {
        this.nome = nome;
    }

    @Override
    public String getEquipe() {
        return equipe;
    }

    @Override
    public void setEquipe(String equipe) {
        this.equipe = equipe;
    }

    @Override
    public double getPontos() {
        return pontos;
    }

    @Override
    public void setPontos(double pontos) {
        this.pontos = pontos;
    }

    public int compareTo(PilotoEquipe piloto) {
        if(this.getPontos() > piloto.getPontos())
            return -1;
        else if(this.getPontos() == piloto.getPontos())
            return 0;
        else
            return 1;
    }
}

Running Class X1:

public class CorridaX1 {
    PilotoEquipeInterface[] p = new PilotoEquipeInterface[20];

    public void exibePilotos(){
        int i = 0;
        while(p[i] != null && i<p.length){
            int numero = i+1;
            System.out.println("Piloto "+numero+":");
            System.out.println("Nome: "+p[i].getNome());
            System.out.println("Equipe: "+p[i].getEquipe());
            System.out.println("----------------------------");
            i++;
        }
    }

    public void orderna(){
        Arrays.sort(p);
    }
}

Class ControlFederation (main)

public class ControleFederacao {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in); 

        CorridaX1 c = new CorridaX1();

            System.out.println("Digite o nome: ");
            String nome = scanner.nextLine();
            System.out.println("Digite a equipe: ");
            String equipe = scanner.nextLine();
            System.out.println("Digite os pontos do piloto: ");
            double pontos = scanner.nextDouble();

            PilotoEquipe piloto = new PilotoEquipe(nome, equipe, pontos);
            c.p[0] = piloto;


        System.out.println("Antes da Ordenacao: ");
        c.exibePilotos();

        System.out.println("Apos a Ordenacao: ");
        c.orderna();
        c.exibePilotos();
    }
}
    
asked by anonymous 10.09.2014 / 01:49

1 answer

4

I found three problems in your code, the first one is in the CorridaX1 class. When you do:

while(p[i] != null && i<p.length){

You're likely to get a ArrayIndexOutOfBoundsException because you first try to access an element in the p array, and then you check whether i still represents a valid element index within your p vector, so you can try to access an element of p beyond the maximum amount it supports. Change this line by the code below that you will be free of this problem:

while(i<p.length && p[i] != null){

The second problem is what causes your NullPointerException . You create a vector of twenty positions of type PilotoEquipeInterface, however you create only a single object of type PilotoEquipe, and leave the other nineteen positions of the vector referencing null. Then you call the sort() method, when it tries to sort the vector it comes up with some null references and then you get the exception.

You may have made this mistake because you wanted to do a test of inserting just one element before creating your loop repetition, so a possible solution is to make your reference variable p have valid references to objects of type PilotoEquipe.

The third problem is that you use nextDouble() to read the points, however you:

1) You are not sure that the user will enter a double when prompted;

2) If the user types a double, you are ignoring the subtraction of the line, which has a \n character, which was produced by pressing ENTER . You should treat it, otherwise you will not be able to enter the name of the next pilot.

Two possible solutions:

    for(int i=0; i<c.p.length; i++) { //o for elimina o primeiro e o segundo problemas
        System.out.println("Digite o nome: ");
        String nome = scanner.nextLine();
        System.out.println("Digite a equipe: ");
        String equipe = scanner.nextLine();
        System.out.println("Digite os pontos do piloto: ");
        double pontos = scanner.nextDouble();
        scanner.nextLine(); //uma solução rápida para o terceiro problema

        PilotoEquipe piloto = new PilotoEquipe(nome, equipe, pontos);
        c.p[i] = piloto;
    }

Or the way I prefer:

    for(int i=0; i<c.p.length; i++) {
        System.out.println("Digite o nome: ");
        String nome = scanner.nextLine();
        System.out.println("Digite a equipe: ");
        String equipe = scanner.nextLine();
        System.out.println("Digite os pontos do piloto: ");
        String linha = scanner.nextLine();
        double pontos;
        try {
            pontos = Double.parseDouble(linha);
        } catch (NumberFormatException e) {
            //aqui você pode atribuir um valor padrão para os pontos
            /* Exemplo
            pontos=1.0;
            */
            //ou interromper o programa com uma mensagem de erro
            /* Exemplo
            System.out.println("Valor inválido para pontos");
            return;
            */
            //ou então insistir até que o usuário entre com um double para os pontos
        }

        PilotoEquipe piloto = new PilotoEquipe(nome, equipe, pontos);
        c.p[i] = piloto;
    }

Related question that may help you understand the third problem:

Using the Java Scanner

    
10.09.2014 / 12:42