Fig. 1. Resultado del ordenamiento en Java
El ejemplo de ordenamiento lo implementé directamente sobre el método principal de una clase. Este es el código:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ordenarnombres;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Balam-PC
*/
public class OrdenarNombres {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
List<String> nombres = new ArrayList<String>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int opcion = 0;
int numeroInserciones = 0;
try {
do{
System.out.println("============== MENU ==============\n");
System.out.println("1) Insertar nombres");
System.out.println("2) Imprimir nombres");
System.out.println("3) Ordenar nombres");
System.out.println("4) Salir\n");
System.out.println("Inserta la opción (1, 2, 3 ó 4): ");
opcion = Integer.parseInt(br.readLine());
switch(opcion){
case 1:
System.out.println("¿Cuántos nombres deseas insertar? ");
numeroInserciones = Integer.parseInt(br.readLine());
for (int i = 0; i < numeroInserciones; i++) {
System.out.println("Nombre [" + (i+1) + "]: ");
nombres.add(br.readLine());
}
break;
case 2:
System.out.println("Nombres:");
for (String str : nombres) {
System.out.println(str);
}
System.out.println("Presione enter para continuar...");
br.readLine();
break;
case 3:
Collections.sort(nombres);
System.out.println("Arreglo ordenado. Presione enter para continuar...");
br.readLine();
break;
}
}while(opcion != 4);
} catch (IOException ex) {
Logger.getLogger(OrdenarNombres.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Les dejo el proyecto; está hecho en NetBeans 7.4:
No hay comentarios.:
Publicar un comentario