Comparable and Arrays.Sort

Asked

Viewed 213 times

2

I’m having difficulties in using the similar interface, I must perform the increasing comparison of drivers according to their score (class PilotoEquipe), and then in class CorridaX1, need to use the Arrays.sort to organize the pilot array. When running the Arrays.sort I get the following error:

Exception in thread "main" java.lang.Nullpointerexception at java.util.Comparabletimsort.countRunAndMakeAscending(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.ControlionFederacao.main(Controlpower.java:35) Java Result: 1

Class Pilotoequipe:

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;
    }
}

Corridax1:

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 Control Power(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();
    }
}
  • Place the contents of the Control.java class and where is line 35 so we can help you. Being Nullpointer, I believe error is simple.

  • 1

    The error is in logic within its main method, in the Control-Factor class. Please click [Edit] and add the code of this class so that we can help.

  • Be careful when instantiating this 20 position array, if you leave any unfilled positions will cause this NPE. If the number of objects in the class PilotoEquipeInterface is dynamic use a ArrayList for example.

  • 3

    As already said, most likely your problem is null positions in the array (since the error occurs in itself sort, and not in your code). And I would like to complement with a detail: avoid returning 0 in the compareTo unless the objects are in fact equal (i.e. a.equals(b) return true). In your case this is not so important, because you are only using the method sort, but if you used these objects as the key to a TreeSet, TreeMap or similar behaviour (inconsistency between the compareTo and the equals) would cause problems. Choose a "tiebreaker criterion"...

  • I put my main class (Control Power) up there too! Thanks a lot!

1 answer

4


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

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

You are likely to receive one ArrayIndexOutOfBoundsException, because you first try to access an element in the array p, and then you check if the i still represents a valid element index within its vector p, this way you can try to access an element of p beyond the maximum amount it supports. Change this line by the code below you will be free of this problem:

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

The second problem is what originates your NullPointerException. You create a twenty position vector of the Pilotoequipeinterface type, however you create only one Pilototeam type object, and leave the other nineteen positions of the zero referencing vector. Then you call the method sort(), when it tries to sort the vector it comes across some null references and then you get the exception.

You possibly made this mistake because you wanted to make a test to insert only one element before creating your repeat loop, so one possible solution is to make your reference variable p has valid references for objects of type Pilotoequipe.

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

1) Not sure that the user will enter with a double when asked;

2) If the user type a double, you will be ignoring the rest of the line, which has a character \n, which was produced by pressing the ENTER. You must treat it, otherwise you will not be able to enter with the name of the next driver.

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 can help you understand the third problem:

How to use the Java scanner

Browser other questions tagged

You are not signed in. Login or sign up in order to post.