如何比较不等长字符串数组的元素?

时间:2015-02-16 05:36:49

标签: java arrays

如何逐个比较不同长度的两个不同String数组的元素。

  import java.util.List;
  import java.util.Scanner;


    public class ArrayComparison {

        public static void main(String[] args) {

            String list1[] = {"m99076", "m10141", "o87909", "o90876", "l17237"};
            String list2[] = {"1", "foo", "1", "m10141", "s3002", "bar", "1", "u39392", "n6233", "fubar", "1", "o87909", "z039"};


            for(int i = 0; [i] < list1; i++){
                for(int j = 0; [j] < list2; j++){

                }if (list1[i] == list2[j]);
                System.out.println("The values are equal");
            } else
                list1[i] != list2[j];
            }
    }

1 个答案:

答案 0 :(得分:0)

你会像这样循环遍历数组,使用“.equals()”比较方法比较每个String。

     String list1[] = {"m99076", "m10141", "o87909", "o90876", "l17237"};
     String list2[] = {"1", "foo", "1", "m10141", "s3002", "bar", "1", "u39392", "n6233", "fubar", "1", "o87909", "z039"};

     for (int i = 0; i < list1.length; i++) {
         for (int a = 0; a < list2.length; a++) {

             if (list1[i].equals(list2[a])) {
                 System.out.println("\"" + list1[i] + "\" is equal to \"" + list2[a] + "\"");
             } else {
                 System.out.println("\"" + list1[i] + "\" is not equal to \"" + list2[a] + "\"");
             }

         }
     }

以下输出如下:

"m99076" is not equal to "1"
"m99076" is not equal to "foo"
"m99076" is not equal to "1"
... lots of lines redacted, until it gets to the first equals ...
"m10141" is equal to "m10141"

此处的完整输出程序:http://pastebin.com/ayaMA0Fk

此外,您的许多语法都不正确。您应该在这里阅读Java语法的基础知识:http://introcs.cs.princeton.edu/java/11cheatsheet/