Sort string array alphabetically

-1

This is a method that orders a string array using an algorithm, but apparently the code it uses shows an error in the comparison of the if

public void ordenar (Array3 a) {
    String buffer = null;
    int i =0;
    while ( i< a.getArreglo().length) {
        int j=0;
        while (j<i) {
            if (a.getArreglo(i)<a.getArreglo(j)) {
                buffer = a.getArreglo(j);
                a.setArreglo(j,a.getArreglo(i));
                a.setArreglo(i,buffer);
            }
            j++;
        }
    i++;
    }


}

Edit: I'm sorry for being unclear, I'm pretty new to this, the error that marks "The operator is undefined for the argument type (s) java.lang.String" I'm sorry if I do not put the whole program, but it's very extensive.

    
asked by Star Hikari 16.11.2018 в 04:06
source

3 answers

1

This is the classic sorting by the bubble method:

Use in your IF compareToIgnoreCase to be able to compare the values of the array for each for cycle and determine the positions of these:

if(vector[i].compareToIgnoreCase(vector[j]) < 0)


//Clase MAIN

//paquetes para la lectura de las cadenas a ingresar en el vector
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main {
   public static void main(String[] args){
      //un objeto bufferedreader que recibe como parámetro un inputstreamreader para almacenar cada entrada que pidamos al usuario al vector.
      BufferedReader in = new BufferedReader (new InputStreamReader (System.in));

      try{
         //contador para llevar el control de las cadenas a ingresar
         int contador = 0;
         //vector de 6 posiciones tipo string
         String []vector = new String[6];
         //instanciamos un objeto de la clase burbuja
         Burbuja obj = new Burbuja(vector);
         //mientras el contador sea diferente de 6, seguimos pidiendo el ingreso de una nueva cadena
         while (contador != 6){
            //solicitud de la cadena
            System.out.println("Ingresa una cadena: ");
            //la posición n del vector será igual a la posición según contador y según la cadena que se lea en la petición anterior
            vector[contador] = in.readLine();
            //aumentamos el contador en uno
            contador++;
         }
         //del objeto instanciado de la clase burbuja invocamos el método ordenar
         obj.ordenar();
         //del objeto instanciado de la clase burbuja invocamos el método mostrar
         obj.mostrar();
      }catch(Exception e){
         System.out.println("Error: " + e);
      }
   }
}


//Clase Burbuja

public class Burbuja{
   un vector de tipo string
   private String vector[];

   //constructor
   public Burbuja(String vector[]){
      this.vector = vector;
   }

   //método ordenar
   public void ordenar(){
      //primer ciclo para recorrer el vector
      for(int i = 0; i < vector.length; i++){
         //segundo ciclo para recorerr el vector y verificar que el valor de i en el primer ciclo sea diferente al valor de j de este segundo ciclo
         for(int j = 0; j < vector.length && i != j; j++){
            //comparamos las posiciones de cada ciclo para saber que valor va alfabéticamente antes que el otro
            if(vector[i].compareToIgnoreCase(vector[j]) < 0){
               //variable auxiliar para guardar el valor de i
               String aux = vector[i];
               //cambio de posiciones
               vector[i] = vector[j];
               vector[j] = aux;
            }
         }
      }
   }

   //método para mostrar el arreglo o vector
   public void mostrar(){
      //ciclo foreach para recorrer el vector e imprimir la posición
      for(String a : vector){
         System.out.println(a);
      }
   }
}

You can also find this on YouTube, there are a lot of video tutorials

Best regards,

    
answered by 16.11.2018 в 05:22
0

I'm not sure what you mean, I hope you can be clearer, in the same way here I leave an example of ordering (It is ordered considering only the first letter of the name):

String [] nombres = {"Zack","Isaac","Ulises","Eduardo","Alejandro"};
    /* 
        Para realizar una comparacion de un elemento con todos los demas 
        elementos de un array se utiliza doble for tambien conocido
        como:  "Metodo burbuja" (no recomendable para el procesamiento de
                grandes sifras de datos).
    */
    for (int i = 0; i < nombres.length; i++) {
        for (int j = 0; j < nombres.length; j++) {
           String temporal;
           if(nombres [i].charAt(0)<nombres[j].charAt(0)){ //Recorremos los menores a la izquierda 
               temporal = nombres[i];
               nombres[i] = nombres[j];
               nombres[j] = temporal;
           }
        }
    }
    // Comprobacion de ordenamiento
    for (int i = 0; i < nombres.length; i++) {
        System.out.println(nombres[i]);
    }
    
answered by 16.11.2018 в 05:17
0

Of course, because to know if a String is smaller, greater or equal to another, you must use the compareTo method that implements the String of the Comparable interface.

    
answered by 18.11.2018 в 05:02