Inverter números no java

1 resposta
peresjuliao

Olá pessoal?

Estava aqui de bobeira sem nada pra fazer então resolvi fazer um daqueles exercícios que nos tomam grande parte de nosso tempo.
Achei um exercício aqui de muito tempo atrás que para ser solucionado é utilizado o famoso algoritmo da bolha.

Mas dando uma lida na API do Java consegui achar um método que resolve boa parte desse problema.
Segue abaixo o código

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

import javax.sound.sampled.ReverbType;

public class Num {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int[] vet = new int[100];
		int condicao = 1;
		int i = 0;
		int opcao = 0;

		while (condicao == 1) {
			System.out.print("DIGITE UM NÚMERO.: ");
			vet[i] = sc.nextInt();
			i++;
			System.out.println("DESEJA CONTINUAR DIGITANDO NÚMERO? (1) - SIM / (2) - NÃO");
			condicao = sc.nextInt();
		}
		
		System.out.println("DESEJA ORDENAR ou REVERTER");
		opcao = sc.nextInt();
		
		if (opcao == 1) {
			Arrays.sort(vet);
		} else if (opcao == 2) {
			// REVERTER
		}
		
		

	}

}

enfim a minha dúvida existe algum método pronto para fazer isso?

1 Resposta

andeb

Na Apache Commons Lang tem um método que faz isso:

/** 
     * <p>Reverses the order of the given array.</p>
     *
     * <p>There is no special handling for multi-dimensional arrays.</p>
     *
     * <p>This method does nothing for a <code>null</code> input array.</p>
     * 
     * @param array  the array to reverse, may be <code>null</code>
     */
    public static void reverse(Object[] array) {
        if (array == null) {
            return;
        }
        int i = 0;
        int j = array.length - 1;
        Object tmp;
        while (j > i) {
            tmp = array[j];
            array[j] = array[i];
            array[i] = tmp;
            j--;
            i++;
        }
    }
Criado 8 de maio de 2010
Ultima resposta 8 de mai. de 2010
Respostas 1
Participantes 2