为什么A == A评估为假?

时间:2015-02-06 04:03:47

标签: java arrays if-statement for-loop

我正在开发一个Java程序,它接受一个名为input的输入String,它看起来像

'(A A A A B C C D E E E E)

我的输出,A String []称为Letters,看起来像

[A,B,C,D,A,E]

另一个Array,一个int []调用计数,应该看起来像

[4,1,2,1,2,4]

我的代码如下所示,但出于某种原因,每次运行它都无效。 print语句读取它不会转到if语句。第二个循环的第2行显示:

  

检查A == A

然后转到else语句并打印

  

A!= A

我做错了什么?为什么A(item [0])不等于A(checkagainst)?

 private static boolean func2(String input){ /*input: '(A A A A B C C D E E E E)
    input = input.replace("'","");//replace to null char
    input = input.replace("(","");//replace to null char
    input = input.replace(")","");//replace to null char
    System.out.println(input);
    String[] items = input.split(" |\u0000",0);
    System.out.println("Array items "+Arrays.toString(items));

    int position = 0;
    int countlength = 0; for (String z: items)countlength += 1;//determines the MAX length of the letters array
    String checkagainst = "";
    String[] letters = new String[countlength];
    int[] count = new int[countlength];
    System.out.println("\n Letters: "+Arrays.toString(letters)
            +"\nCount: "+Arrays.toString(count)
            +"\nItems: "+Arrays.toString(items));
    for (int x = 0; x < items.length; x++){
        System.out.println("\n\nCheck if"+checkagainst+"=="+items[x]);
        if (checkagainst == items[x]){
            count[position] += 1;
            System.out.println("Iteration:" + x
                    +"\n Letters: "+Arrays.toString(letters)
                    +"\n Count: "+Arrays.toString(count)
                    +"\nSwitch: if");
        }
        else{
            System.out.println("checkagainst != items[x]");
            letters[position] = items[x];
            count[position] = 1;
            checkagainst = items[x];
            position ++;
            System.out.println("Iteration:" + x
                                +"\n Letters: "+Arrays.toString(letters)
                                +"\n Count Arrays"+Arrays.toString(count)
                                +"\ncheckagainst: "+ checkagainst
                                +"\nSwitch: else");
        }
    }

0 个答案:

没有答案