Java - Verificar se há valores repetidos em 1 vetor

02/10/2017

0

Foi me passado a seguinte questão:
Leia uma lista de 10 posições e verifique se existem valores iguais e os escreva.
Só que infelizmente o burro aqui não conseguiu

Eu tentei isso aqui:

	private static void preencher() {
		// TODO Auto-generated method stub
		String aux="Valores que são iguais:\\n";
		int igual;
		for(int i=0;i<10;i++)
		vetor[i]=Integer.parseInt(JOptionPane.showInputDialog("Informe o "+(i+1)+"º valor"));
		
		for (int i=0;i<10;i++) {
			for (int j=0;j<9;j++) {
				if(vetor[i]==vetor[j+1]) {
					igual=vetor[i];
					aux+=igual+"\\n";
				}//if
			}//fim do 2 for
				
		}//fim do for
		JOptionPane.showMessageDialog(null, aux);
	}


Mas não consegui o que queria :(
Henrique Marino

Henrique Marino

Responder

Posts

02/10/2017

Suzane Soares


Acho que é isso:



import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JOptionPane;



public class Main {


       public static void preencher(){
       int vetor[] = new int[10];
             ArrayList<Integer> lista = new ArrayList<Integer>();
             
             String aux = "Valores que são iguais: ";
             
             JFrame frame = new JFrame("InputDialog Example #1");
             
             
       
             for (int i = 0; i < vetor.length; i++) {
                    vetor[i] = Integer.parseInt(JOptionPane.showInputDialog(frame, "Insira um número"));
       
             }
             
             for (int i = 0; i < vetor.length; i++) {
                    
                    
                                  for (int j = 0; j < vetor.length; j++) {
                                        
                                        if(vetor[i]==vetor[j]&& j!=i){
                                               if(!lista.contains(vetor[i]))
                                               {
                                                      lista.add(vetor[i]);
                                                      
                                               }
                                        }
                                        
                                        
                                  }            
                    
                                        
             }
             
             for (Integer integer : lista) {
                    aux+=integer+",";
             }
             JOptionPane.showMessageDialog(new JFrame(), aux);
       }


       public static void main(String[] args) {
             Main.preencher();
       }
}

Responder

Assista grátis a nossa aula inaugural

Assitir aula

Saiba por que programar é uma questão de
sobrevivência e como aprender sem riscos

Assistir agora

Utilizamos cookies para fornecer uma melhor experiência para nossos usuários, consulte nossa política de privacidade.

Aceitar