Logica em while(ajuda)

3 respostas
G

Tenho que fazer uma rotina com o while que pede 4 numeros digitados pelo usuario e diga o maior e seu segundo maior numero.

tentei com if mas não esta dando certo.

Usei está logica abaixo, mas não deu certo.

while(cnt<=4)

{	

a = javax.swing.JOptionPane.showInputDialog("Escreva os numeros: ");

num = Integer.parseInt(a);

if(num>maior)

{

maior = num;

}

if(maior>seg_maior)

{

seg_maior = maior;

}

3 Respostas

eltonk
int maior=0;
int maior2=0;
int aux=0;
for (int i=0; i<4; i++){
   aux=Integer.parseInt(JOptionPane.showInputDialog("Entre com o numero "+(i+1)));
   if (aux > maior){
      maior2 = maior;
      maior = aux;
   }else if (aux > maior2){
         maior2 = aux;
   }
}
System.out.println("Maiores # são: "+maior+" e "+maior2);
F

“eltonk”:
int maior=0; int maior2=0; int aux=0; for (int i=0; i<4; i++){ aux=Integer.parseInt(JOptionPane.showInputDialog("Entre com o numero "+(i+1))); if (aux > maior){ maior2 = maior; maior = aux; }else if (aux > maior2){ maior2 = aux; } } System.out.println("Maiores # são: "+maior+" e "+maior2);

Desse jeito não vai funcionar se todos os números forem negativos:

int maior=Integer.parseInt(JOptionPane.showInputDialog("Entre com o numero 1"));
int maior2=Integer.parseInt(JOptionPane.showInputDialog("Entre com o numero 2"));
int aux;
if (maior2 > maior){
 aux = maior;
 maior = maior2;
 maior2 = aux;
}
for (int i=2; i<4; i++){
   aux=Integer.parseInt(JOptionPane.showInputDialog("Entre com o numero "+(i+1)));
   if (aux > maior){
      maior2 = maior;
      maior = aux;
   }else if (aux > maior2){
         maior2 = aux;
   }
}
eltonk

pah…

fiz em 30 segundos a bagaça e sem testar… :roll:

Faltou um teste unitário no método hahahaha

Criado 31 de julho de 2005
Ultima resposta 31 de jul. de 2005
Respostas 3
Participantes 3