如何比较Arraylist中不同数组的两个元素?

时间:2015-05-30 18:45:42

标签: java arrays arraylist

我已经使用ArrayList(java),aList1aList2创建了两个数组。两者都将混合使用双打和弦乐。如何直接将aList1的个别内容与aList2中相应的个别内容进行比较。例如,如果aList1中的第一个值或字符串与第一个值不匹配或aList2中的字符串,应该有一条消息说两者不匹配。这应该在每个ArrayList的每个元素上继续。

谢谢!

编辑:

这是我最初的尝试:

if (!aList1.get(0).equals(aList2.get(0))) { 
     JOptionPane.showMessageDialog(null,  "#1 is incorrect.");
}
if (!aList1.get(1).equals(aList2.get(1))) {
     JOptionPane.showMessageDialog(null, "#2 is incorrect.");
}

依此类推,通过比较aList1和aList2中的每个元素,看看它们是否相等(无论它们是双精度型还是字符串)。相应的元素和数组的大小将始终相同。因此,例如,如果aList1 = {0,1,2,3,4,dog},则aList2可以包含{10,2,5,2,cat}。

编辑:整个代码。

import javax.swing.JOptionPane;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.ArrayList;

public class KevinMath2 {
        static File filename = new File("homework.txt");
        static ArrayList <Object> aList = new ArrayList <Object> ();
        static String homework = " ";
        static File filename2 = new File("homework2.txt");
        static ArrayList <Object> aList2 = new ArrayList <Object> ();
        static String homework2 = " ";
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String initialInput = JOptionPane.showInputDialog(null, "Would you like to add answers or check answers?");
        String again;
        char repeat;
        do {
            switch (initialInput) {
                case "Add answers":
                    char answerfinal1;
                    String answerPass = JOptionPane.showInputDialog(null, "Please enter the password");
                    while (!answerPass.equals("Victor")) {
                        JOptionPane.showMessageDialog(null,  "Incorrect Password. Please try again.");
                        answerPass = JOptionPane.showInputDialog(null, "Please enter the password.");
                    }
                    do {
                        do {
                            String options = JOptionPane.showInputDialog(null, "Enter the date of the desired" +
                                                                            " answers to add (M/D/Y)");
                            switch (options) {
                                case "05/29/15":
                                    while (!homework.isEmpty()) {
                                        homework = JOptionPane.showInputDialog("Please enter the answers, in order. After "
                                                                                + "the last answer, leave the next answer" 
                                                                                + " blank, and click OK.");
                                        if (!homework.isEmpty()) aList.add(homework);
                                    }
                                    try {
                                        FileWriter fw = new FileWriter (filename);
                                        Writer output = new BufferedWriter (fw);
                                        int sz = aList.size();
                                        for (int i=0; i < sz; i++) {
                                            output.write(aList.get(i).toString() + "\n");
                                        }
                                        output.close();
                                    } catch (Exception e) {
                                        JOptionPane.showMessageDialog(null, "Oops! I cannot create that file.");
                                    }
                                    break;
                                default:
                                    JOptionPane.showMessageDialog(null,  "Please enter a valid date.");
                                    break;
                            }
                        } while (!homework.isEmpty());
                        String final1 = JOptionPane.showInputDialog(null, "Is this correct: " + aList.get(0) + " "
                                                                        + aList.get(1) + " " + aList.get(2) + " " + 
                                                                        aList.get(3) + " " + aList.get(4) + "? (Yes or No)");
                        answerfinal1 = final1.charAt(0);
                    } while (answerfinal1 == 'n' || answerfinal1 == 'N');

                    break;
                    //Need to store the array permanently
                case "Check answers": //Need to make it so it stores array of Kevin's answers permanently
                    char answerfinal2;
                    String checkPass = JOptionPane.showInputDialog(null, "Please enter the password");
                    while (!checkPass.equals("Kevin")) {
                        JOptionPane.showMessageDialog(null,  "Incorrect Password. Please try again.");
                        answerPass = JOptionPane.showInputDialog(null, "Please enter the password.");
                    }   
                    do {
                        do {
                            String options2 = JOptionPane.showInputDialog(null, "Enter the date of the desired" +
                                                                            " answers to check (M/D/Y)");
                            switch (options2) {
                                case "05/29/15":
                                    while (!homework2.isEmpty()) {
                                        homework2 = JOptionPane.showInputDialog("Please enter the answers, in order. After "
                                                                            + "the last answer, leave the next answer" +
                                                                             " blank, and click OK.");
                                        if (!homework2.isEmpty()) aList2.add(homework2);
                                    }
                                    try {
                                        FileWriter fw = new FileWriter (filename2);
                                        Writer output = new BufferedWriter (fw);
                                        int sz = aList2.size();
                                        for (int i=0; i < sz; i++) {
                                            output.write(aList2.get(i).toString() + "\n");
                                        }
                                        output.close();
                                    } catch (Exception e) {
                                        JOptionPane.showMessageDialog(null, "Oops! I cannot create that file.");
                                    }
                                    break;
                                default:
                                    JOptionPane.showMessageDialog(null,  "Please enter a valid date.");
                            }
                        } while (!homework2.isEmpty());
                        String final2 = JOptionPane.showInputDialog(null, "Is this correct: " + aList2.get(0) + " "
                                + aList2.get(1) + " " + aList2.get(2) + " " + 
                                aList2.get(3) + " " + aList2.get(4) + "? (Yes or No)");
                        answerfinal2 = final2.charAt(0);
                    } while (answerfinal2 == 'n' || answerfinal2 == 'N');

                    int i = 0; // counter variable


                    if (aList.size() == aList2.size()) { // Check if both lists are equal
                        for (Object obj : aList) { // iterate through any list
                            if (obj.getClass() == String.class) { // find if it's a string
                                if (!aList.get(i).equals(aList2.get(i))) {
                                    JOptionPane.showMessageDialog(null, "#" + i + " is wrong.");
                                }

                            }

                            if (obj.getClass() == Double.class) { // or a double
                                if (!aList.get(i).equals(aList2.get(i))) {
                                    JOptionPane.showMessageDialog(null, "#" + i + " is wrong.");
                                }
                            }

                            i++;
                        }
                    }

                    break;
                default:
                    JOptionPane.showMessageDialog(null, "Please enter a valid option.");
                    break;
                } 
            again = JOptionPane.showInputDialog(null, "Would you like to check another answer, or "+
                                                    "add another answer? (Yes or No)");
            repeat = again.charAt(0);
        } while (repeat == 'y' || repeat == 'Y');
        JOptionPane.showMessageDialog(null,  "Thanks for using this program");

    }

}

5 个答案:

答案 0 :(得分:2)

尝试使用for循环迭代第一个ArrayList并使用for循环中的计数器(以下示例中的#);来比较使用get方法循环的每个索引由ArrayList提供。

for (int i = 0; i < aList1.size(); i++) {
    if (!aList1.get(i).equals(aList2.get(i)))
        //output whatever you want it to say
}

编辑:更改为.equals而不是==作为建议。好抓。

答案 1 :(得分:0)

比较列表中两个元素的数据类型,如果它们匹配,则尝试比较它们的内容 要比较数据类型,请遵循以下提到的代码

    int a = 10;
    Object o = a;
    System.out.println(o.getClass().getSimpleName());

如果数据类型匹配,则尝试比较其内容

答案 2 :(得分:0)

我同意coal175s的答案,但既然你说你在数组列表中混合了类型,你应该使用.equals()方法来比较它们。

if !(aList1.get(i).equals(aList2.get(i))) {

答案 3 :(得分:0)

您应该使用List通用语Object初始化您的List<Object> list = new ArrayList<>();对象,以便在列表中添加StringDouble

这是比较两个阵列的理想解决方案。

List<Object> aList1 = new ArrayList<Object>();
List<Object> aList2 = new ArrayList<Object>();

aList1.add("abc");
aList1.add(25);

aList2.add("abc");
aList2.add(25);

int i = 0; // counter variable

if (aList1.size() == aList2.size()) { // Check if both lists are equal
    for (Object obj : aList1) { // iterate through any list

        if (obj.getClass() == String.class) { // find if it's a string
            if (aList1.get(i).equals(aList2.get(i))) {
                JOptionPane.showMessageDialog(null, (i+1) + " is correct.");
            } else {
                JOptionPane.showMessageDialog(null, (i+1) + " is incorrect.");
            }

        }

        if (obj.getClass() == Double.class) { // or a double
            if (aList1.get(i).equals(aList2.get(i))) {
                JOptionPane.showMessageDialog(null, (i+1) + " is correct.");
            } else {
                JOptionPane.showMessageDialog(null, (i+1) + " is incorrect.");
            }
        }

        if (obj.getClass() == Integer.class) {
            JOptionPane.showMessageDialog(null, "Integer is found");
        }

        i++;
    }
}

您的代码很难遵循,当您编写程序时,请尝试遵循Java惯例。

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.ArrayList;

import javax.swing.JOptionPane;

public class KevinMath2 {
    static File filename = new File("homework.txt");
    static ArrayList<Object> aList = new ArrayList<Object>();
    static String homework = "";
    static File filename2 = new File("homework2.txt");
    static ArrayList<Object> aList2 = new ArrayList<Object>();
    static String homework2 = "";
    static String answerPass = "";
    static final int TOTAL_QUESTIONS = 5;

    public static void main(String[] args) {
        String initialInput = JOptionPane.showInputDialog(null,
                "Enter Add answers / Check answers to continue");

        switch (initialInput) {
        case "Add answers":
            answers("Victor", aList, filename);

            int choice = JOptionPane.showConfirmDialog(null,
                    "Would you like to compare your answers?", "Yes/No", JOptionPane.YES_NO_OPTION);
            if (choice == JOptionPane.YES_OPTION) {
                answers("Kevin", aList2, filename2);
                checkAnswers(aList, aList2);
            }
            break;

        // Need to store the array permanently
        case "Check answers": // Need to make it so it stores array of
                                // Kevin's answers permanently
            answers("Kevin", aList2, filename2);

            if (aList.size() == 0) {
                JOptionPane.showMessageDialog(null,
                        "Please add answers to compare.");
                answers("Victor", aList, filename);
            }
            checkAnswers(aList, aList2);
            break;

        default:
            JOptionPane.showMessageDialog(null, "Please enter a valid option.");
            break;
        }

        // exit the program
        JOptionPane.showMessageDialog(null, "Thanks for using this program");

    }

    public static void answers(String pass, ArrayList<Object> list, File f) {

        answerPass = JOptionPane.showInputDialog(null,
                "Please enter the password");
        // validate user
        while (!answerPass.equals(pass)) {
            JOptionPane.showMessageDialog(null,
                    "Incorrect Password. Please try again.");
            answerPass = JOptionPane.showInputDialog(null,
                    "Please enter the password.");
        }

        // add answers
        String final1 = "";
        do {
            clearFile(f);
            list.clear();

            // validate the date of the answers
            String options = JOptionPane.showInputDialog(null,
                    "Enter the date of the desired" + " answers (MM/DD/YY)");
            // add your answers
            enterAnswers(options, list, f);

            // verify the answers
            final1 = JOptionPane.showInputDialog(null, "Is this correct: "
                    + list.get(0) + " " + list.get(1) + " " + list.get(2) + " "
                    + list.get(3) + " " + list.get(4) + "? (Y/N)");

        } while (final1.charAt(0) == 'n' || final1.charAt(0) == 'N');

    }

    public static void enterAnswers(String options, ArrayList<Object> list,
            File f) {

        switch (options) {
        case "05/29/15":
            boolean valid = false;

            for (int i = 0; i < 5; i++) {
                while (!valid) {
                    homework = JOptionPane
                            .showInputDialog("Please enter your answer for question "
                                    + (i + 1));
                    if (!homework.isEmpty())
                        valid = true;
                }
                list.add(homework);
                valid = false;
            }

            writeFile(f, list); // write the answers to a file

            break;

        default:
            JOptionPane.showMessageDialog(null, "Please enter a valid date.");
        }
    }

    public static void writeFile(File filename, ArrayList<Object> list) {
        try {
            FileWriter fw = new FileWriter(filename);
            Writer output = new BufferedWriter(fw);

            for (int j = 0; j < list.size(); j++) {
                output.write(list.get(j) + "\n");
            }
            output.close();

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null,
                    "Oops! I cannot create that file.");
        }
    }

    public static void clearFile(File filename) {
        try {
            FileWriter fw = new FileWriter(filename);
            Writer output = new BufferedWriter(fw);
            output.write("");
            output.close();

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null,
                    "Oops! I cannot create that file.");
        }
    }

    public static void checkAnswers(ArrayList<Object> a, ArrayList<Object> b) {
        int i = 0; // counter variable

        if (a.size() == b.size()) { // Check if both lists are
                                    // equal
            for (Object obj : a) { // iterate through any list
                if (obj.getClass() == String.class) { // find if it's a
                                                        // string
                    if (!a.get(i).equals(b.get(i))) {
                        JOptionPane.showMessageDialog(null, "#" + i
                                + " is wrong.");
                    }

                }

                if (obj.getClass() == Double.class) { // or a double
                    if (!a.get(i).equals(b.get(i))) {
                        JOptionPane.showMessageDialog(null, "#" + i
                                + " is wrong.");
                    }
                }

                if (obj.getClass() == Integer.class) { // or an integer
                    if (!a.get(i).equals(b.get(i))) {
                        JOptionPane.showMessageDialog(null, "#" + i
                                + " is wrong.");
                    }
                }

                i++;
            }
        }

    }

}

答案基于假设

  • 添加ArrayList的答案。
  • 比较您在另一个ArrayList中的答案。
  • 您没有比较书面文件中的答案。

您正在撰写已添加的答案&#39;到某个文件,但您不会再次阅读该文件,以便与您的“检查答案”进行比较。要做到这一点,请编写另一种方法来阅读homework.txt文件,将每一行存储到aList,然后与aList2进行比较。

答案 4 :(得分:0)

需要考虑两件事:

  1. 两个ArrayList都具有相同的大小
  2. 当您检查元素时,它们必须是相同的数据类型,还是我们可以将所有内容都转换为String然后进行比较。我将假设它们必须是相同的数据类型。
  3. 说完了:

    java.lang.Integer: 1234 != java.lang.String: 1234
    999 != 9991
    

    结果(来自list1的999.999未被检查):

    $ docker