Search code examples
javaarraysswingjoptionpane

for loop with comparing to set of arrays


Q. what is the right condition for DISPLAYING ONLY equal elements in my array.

heres the code.

    int num[]=new int[5];
    int numm[]=new int[5];

    for(int x=0;x<num.length;x++){
        num[x]=Integer.parseInt(JOptionPane.showInputDialog("Enter Values for num["+(x+1)+"]"));
    }

    for(int x1=0;x1<num.length;x1++){
        num[x1]=Integer.parseInt(JOptionPane.showInputDialog("Enter Values for num1["+(x1+1)+"]"));
    }

    String tosho="";
        for(int a=0;a<num.length;a++){
            for(int a1=0;a1<numm.length;a1++){
            if(num[0]==numm[0]){
              num[0]=numm[0];}


            else if(num[1]==numm[1]){
                num[1]=numm[1];}

            else if(num[2]==numm[2]){
                num[2]=numm[2];}

            else if(num[3]==numm[3]){
                num[3]=numm[3];}

            else if(num[4]==numm[4]){
                num[4]=numm[4];}       
        }

    }tosho+=(num[0])+""+(num[1])+""+(num[2])+""+(num[3])+""+(num[4]);

    JOptionPane.showMessageDialog(null, "both "+tosho+" found in array.");

when I input 1,2,3,4,5 in first aary

then 1,22,3,4,5 in second array

still it display the 2 or 22, even though they are not equal,,,


Solution

  • num[x1]=Integer.parseInt(JOptionPane.showInputDialog("Enter Values for num1["+(x1+1)+"]"));
    

    maybe numm[x1]?

    You can use this code to fill tosho:

    String tosho="";
    for(int a=0;a<num.length;a++) {
        if(num[a]==numm[a]) {
            tosho+=num[a]+",";
        }
    }