Как отобразить, если эти два массива имеют одинаковые номера в одном и том же месте в обоих массивах? - PullRequest
0 голосов
/ 21 мая 2019

Итак, вот моя проблема: у меня есть два массива, я хочу подсчитать, сколько значений находятся в одной и той же позиции [i] в ​​обоих массивах, и сколько значений одинаковы в обоих массивах, но для разных [i]

Я попробовал обычный цикл с for и размер массива, но он отображает странные значения, которые далеки от ожидаемых

package stackOverflow;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class mainStack extends JFrame implements ActionListener {

    JButton jbr,jbv,jbb,jbo,jbn,jbj; 
    JTextField l11b;
    String a;

    int tabRef[]= {0,1,2,3};
    int correctAndSameCase=0;
    int correctButDiffCase=0;
        mainStack(){

            this.setLayout(null);
            jbr = new JButton("Rouge");
            jbr.setBounds(0,80,85,30);
            add(jbr);

            jbv = new JButton("Vert");
            jbv.setBounds(125, 80, 85, 30);
            add(jbv);

            jbb = new JButton("Bleu");
            jbb.setBounds(0, 120, 85, 30);
            add(jbb);

            jbj = new JButton("Jaune");
            jbj.setBounds(125, 120, 85, 30);
            add(jbj);

            jbo = new JButton("Orange");
            jbo.setBounds(0, 160, 85,30);
            add(jbo);

            jbn = new JButton("Noir");
            jbn.setBounds(125,160, 85,30);
            add(jbn);

            jbr.addActionListener(this);
            jbv.addActionListener(this);
            jbb.addActionListener(this);
            jbj.addActionListener(this);
            jbo.addActionListener(this);
            jbn.addActionListener(this);

            setLayout(null);
            setSize(800,800);
            setVisible(true);
        }
        private int index = 0;
        private int p=0;
        private int tabAnswer[][] = new int[3][4];
        private int i;


        public void actionPerformed(ActionEvent e) {
            if (e.getSource().equals(jbr)) {
                tabAnswer[p][index] = 0;
            } else if (e.getSource().equals(jbv)) {
                tabAnswer[p][index] = 1;
            } else if (e.getSource().equals(jbj)) {
                tabAnswer[p][index] = 2;
            } else if (e.getSource().equals(jbb)) {
                tabAnswer[p][index] = 3;
            } else if (e.getSource().equals(jbo)) {
                tabAnswer[p][index] = 4;
            } else if (e.getSource().equals(jbn)) {
                tabAnswer[p][index] = 5;
            }
            index++;
            if (index >= tabAnswer[p].length) {
                System.out.println(Arrays.toString(tabAnswer[p]));

                for(i=0 ; i<tabRef.length;i++) {

                    if(tabAnswer[p][i]==tabRef[i]) {

                        correctAndSameCase++;
                    }else if(tabAnswer[p][i]==tabRef[0] & tabAnswer[p][i]!=tabRef[i]  ||  tabAnswer[p][i]==tabRef[1] & tabAnswer[p][i]!=tabRef[i] || tabAnswer[p][i]==tabRef[2]& tabAnswer[p][i]!=tabRef[i] ||tabAnswer[p][i]==tabRef[3] & tabAnswer[p][i]!=tabRef[i]) {

                        correctButDiffCase++;
                    }

                }
                index = 0;
                p++;
                System.out.println(correctAndSameCase+" number are on the same case on both arrays");
                System.out.println(correctButDiffCase+" number are on different case on both arrays");
                if(p>=3) {
                    p=0;
                }
                correctAndSameCase=0;
                correctButDiffCase=0;

            }
        }
    public static void main(String[] args) {
        mainStack t= new mainStack();
}

Здесь для tabAnswer {5,4,3,2} correctAndSameCase должно быть 0 иcorrectButDiffCase должно быть 2, но вместо этого оно дает мне 0 и 1. В качестве ответа.

РЕДАКТИРОВАТЬ: я вижу, что проблема в том, чтобы установить значение correctButDiffCase, но я не знаюкак это исправить

Ответы [ 2 ]

0 голосов
/ 21 мая 2019

Ваш код для подсчета событий кажется нормальным (хотя и немного грязным). Я написал тест junit, используя ваш код, и нет проблем:

  @Test
  public void testArrayCheck() {
    int[] tabRef = {0,1,2,3};
    int tabAnswer[][] = new int[3][4];
    int[] tabAnswerPos0 = {0,0,0,0};
    tabAnswer[0] = tabAnswerPos0;
    int p = 0;
    int correctAndSameCase = 0;
    int correctButDiffCase = 0;
    Set<Integer> setArrayValues = new HashSet<Integer>();
    for(int i=0 ; i<tabRef.length;i++) {
      if(tabAnswer[p][i]==tabRef[i]) {
          correctAndSameCase++;
      }else if(tabAnswer[p][i]==tabRef[0] && tabAnswer[p][i]!=tabRef[i]  
          ||  tabAnswer[p][i]==tabRef[1] && tabAnswer[p][i]!=tabRef[i] 
              || tabAnswer[p][i]==tabRef[2] && tabAnswer[p][i]!=tabRef[i] 
                  ||tabAnswer[p][i]==tabRef[3] && tabAnswer[p][i]!=tabRef[i]) {
          if (!setArrayValues.contains(tabAnswer[p][i])) {
            correctButDiffCase++;
            setArrayValues.add(tabAnswer[p][i]);
          }
      }
    }
  System.out.println(correctAndSameCase+" number are on the same case on both arrays");
  System.out.println(correctButDiffCase+" number are on different case on both arrays");
  }

1 number are on the same case on both arrays
1 number are on different case on both arrays

Вы уверены, что tabAnswers имеет значения {5,4,3,2}?

0 голосов
/ 21 мая 2019

здесь фрагмент кода, который подсчитывает эти два значения. Но я не знал, хотите ли вы подсчитать некоторые особые случаи (см. TODO).

    public static void main(String[] args) throws Exception {

    List<Integer> tabRef =  Arrays.asList(10, 5, 3, 5, 2, 6);
    List<Integer> tabRef2 = Arrays.asList(12, 8, 3, 5, 6, 2);

    int matchesOnSameIndex = 0;
    int matchesButDifferentIndex = 0;

    for (int i = 0; i < tabRef.size(); i++) {
        //compare on same index, if other list has element on this index
        if (tabRef2.size() > i) {
            if (tabRef.get(i) == tabRef2.get(i)) {
                //same element on same index
                matchesOnSameIndex++;
            }
        }

        //check if value exists in other list
        if (tabRef2.contains(tabRef.get(i))) {
            //if yes, check if it is not at same position
            if (tabRef2.size() > i) {
                if (tabRef2.get(i) != tabRef.get(i)) {
                    //not same index
                    //TODO must count multiple times, if element exists multiple times?
                    matchesButDifferentIndex++;
                }else {
                    //TODO must count, if also exists on other index?
                }
            }else {
                //same position not existing, so must be on other position
                matchesButDifferentIndex++;
            }
        }
    }

    System.out.println("matchesOnSameIndex: "+matchesOnSameIndex);
    System.out.println("matchesButDifferentIndex: "+matchesButDifferentIndex);

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...