Find the element with the largest number

3

I am making a basic election system, but I have a problem in telling which candidate was elected. In the case, I added three candidates (x, y, z) in ArrayList , put two votes in the x, three in the y and four in the z. When I want to know what won (in this case the one that got the most votes) it prints all 3 candidates.

public void eleitoPresidente() {
    int maior = 0;
    for (Candidato e: candidato) {
        if(e.votos > maior) {
            maior = e.votos;
            System.out.println("O presidente eleito é: " + e.nome);
        }
    }
}

I want it to print only the candidate with the most votes.

    
asked by anonymous 03.06.2017 / 02:33

3 answers

4

Keeping the algorithm you did initially has two problems, you are not saving which is the largest anywhere. And he is saying who was elected every time a new candidate evaluated has more votes than the previous one. Then the correct one would be:

import java.util.*;

class HelloWorld {
    public static void main (String[] args) {
        ArrayList<Candidato> candidato = new ArrayList<>();
        candidato.add(new Candidato("joao", 4));
        candidato.add(new Candidato("jose", 2));
        candidato.add(new Candidato("joaquim", 7));
        int maiorVotos = 0;
        Candidato maiorCandidato = null;
        for (Candidato e: candidato) {
            if(e.votos > maiorVotos) {
                maiorVotos = e.votos;
                maiorCandidato = e;
            }
        }
        if (maiorCandidato != null) {
            System.out.println("O presidente eleito é: " + maiorCandidato.nome);
        }
    }
}

class Candidato {
    public String nome;
    public int votos;
    public Candidato (String nome, int votos) {
        this.nome = nome;
        this.votos = votos;
    }
}

See running on ideone . And at Coding Ground . Also put it on GitHub for future reference .

    
03.06.2017 / 02:41
2

You can use the Collections.sort(List<T>, Comparator<? super T>) " to sort the candidates by some criteria (in this case the number of votes in descending order), and then get the first of them:

public void eleitoPresidente() {
    List<Candidato> copia = new ArrayList<>(candidato);
    Collections.sort(copia, (a, b) -> b.votos - a.votos);
    System.out.println("O presidente eleito é: " + copia.get(0).nome);
}
    
03.06.2017 / 02:40
1

That way it will work

public void eleitoPresidente() {
    Candidato maiorCand = null;
    int maior = 0;
    for (Candidato e : candidato) {
        if (e.votos > maior) {
            maiorCand = e;
        }
    }
    if (maiorCand != null) {
        System.out.println("O presidente eleito é: " + maiorCand.nome);
    } else {
        System.out.println("Não teve presidente eleito");
    }
}
    
03.06.2017 / 02:36