Operator ">" cannot be used comparing strings

Asked

Viewed 95 times

0

import java.util.Scanner;
public class ordenarNomes{
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String [] nomes = new String [20];

        for(int i=0;i<nomes.length;i++){
            System.out.println("Informe os nomes: ");
            nomes[i] = in.next();
        }
        String x = " ";
        for(int i=1;i<nomes.length-1;i++){
            for(int j=i+1;j<nomes.length;j++){
                if(nomes[i] > nomes[j]){
                    x = nomes[i];
                    nomes[i] = nomes[j];
                    nomes[j] = x;
                }
            }
        }
        for(int i=0;i<nomes.length;i++){
            System.out.print(nomes[i]+" ");
        }
    }    
}

Generating the following error:

The Operator > is Undefined for the argument type(s)

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

3

In Java String is not a type of first class, so it has no operators, and you should compare with the method compareTo():

import java.util.Scanner;

class OrdenarNomes {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String[] nomes = new String[20];
        for (int i = 0; i < nomes.length; i++) {
            System.out.println("Informe os nomes: ");
            nomes[i] = in.next();
        }
        String x = " ";
        for (int i = 0; i < nomes.length - 1; i++) {
            for (int j = i + 1; j < nomes.length; j++) {
                if (nomes[i].compareTo(nomes[j]) > 0) {
                    x = nomes[i];
                    nomes[i] = nomes[j];
                    nomes[j] = x;
                }
            }
        }
        for (int i = 0; i < nomes.length; i++) System.out.print(nomes[i]+" ");
    }    
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Had more mistakes

  • At last for vi that removed the keys, it is only aesthetic or there is something more (better performance, for example)?

Browser other questions tagged

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