Ajuda com vetor, separando números positivos de negativos

2 respostas
F

Bom dia,

Por favor, como exibo os números positivos … no código abaixo eu consigo mostrar todos e logo depois o negativos… minha intenção é mostra-los separados…
Onde estou errando???
Obrigado

import javax.swing.*;
public class Vetor {
	public static void main(String args[]) {
		int A[] = new int[4];
		int B[] = new int[4];
		String strA = "", strB = "";
		int i, j=0;
		for(i=0; i<A.length; i++)
		{
			A[i] = Integer.parseInt(
				JOptionPane.showInputDialog("Entre com o "+(i+1)+"º número:"));
			if(A[i] < 0)
			{
				B[j] = A[i];
				j++;
			}

		}
		for(i=0; i<A.length; i++)
		{
				strA += A[i] + ", ";
		}
		JOptionPane.showMessageDialog(null, "A=" + strA);
		for(i=0; i<j; i++)
		{
				strB += B[i] + ", ";
		}
		JOptionPane.showMessageDialog(null, "B=" + strB);
	}
}

2 Respostas

Vmaia

olá, dei uma olhada por cima e acho que isso resolve, mas existem formas mais eficientes..... só procurar :D

Segue
public static void main(String args[]) {
		int A[] = new int[4];
		int B[] = new int[4];
		int positivos[] = new int[4];
		String strA = "", strB = "", strP=""; 
		int i, j=0,p=0;
		for(i=0; i<A.length; i++)
		{
			A[i] = Integer.parseInt(
				JOptionPane.showInputDialog("Entre com o "+(i+1)+"º número:"));
			if(A[i] < 0)
			{
				B[j] = A[i];
				j++;
			}else {
				// vc não estava limpando o array A removendo os negativos.
				positivos[p] = A[i];
				p++;
			}

		}
		for(i=0; i<A.length; i++)
		{
				strA += A[i] + ", ";
		}
		JOptionPane.showMessageDialog(null, "A=" + strA);
		for(i=0; i<j; i++)
		{
				strB += B[i] + ", ";
		}
		JOptionPane.showMessageDialog(null, "B=" + strB);
		for(i=0; i<j; i++)
		{
			strP += positivos[i] + ", ";
		}
		JOptionPane.showMessageDialog(null, "positivos=" + strP);
	}
F

Obrigao pela ajuda!!!

Só precisei mudar estas linhas:

}if (A[i] > 0){
            positivos[p] = A[i];
            p++;
        }
Criado 11 de junho de 2010
Ultima resposta 11 de jun. de 2010
Respostas 2
Participantes 2