我想比较String数组和String数组,但我没有成功

时间:2013-12-07 09:13:49

标签: java arrays string

String [] abcd={"A","B","C","D","E","F","G","H","I","J","K","L","N","M","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
JButton [] efgh = new JButton[abcd.length];
String [] secretWord={"S","W","I","N","G"};
JTextField [] input= new JTextField[secretWord.length];
String assign;
String [] content = new String[5];

for(int a=0;a<abcd.length;a++)
    {
        if(e.getSource()==efgh[a])
        {
            efgh[a].setEnabled(false);
            if(i<input.length)
            {
                input[i].setText(abcd[a]);
                i++;
            if(i==input.length)
            {   
                for(c=0;c<input.length;c++)
                    {
                        assign=input[c].getText();
                        content[c]=assign;
                        System.out.print(content[c]);

                    }
            }
        }
    }
        if(c==4)
        {
            if(content[0] == secretWord[0]) && content[1]==secretWord[1] && content[2]==secretWord[2] && content[3]==secretWord[3] && content[4]==secretWord[4])
            {
                output1.setText("You are right!!!!");
            }
            else
            {
                output1.setText("Try again!!");
            }
        }

    }   

当用户点击按钮时,我想用secretWord [value]继续执行步骤内容[value],但总是得到“再试一次”..声明我在哪里错了?请我谢谢你非常...... ..

2 个答案:

答案 0 :(得分:3)

欢迎使用StackOverflow!

将字符串与.equals()而不是==

进行比较
if(content[0].equals(secretWord[0])) && .... 

-or-

if(content[0].equalsIgnoreCase(secretWord[0])) && ....

答案 1 :(得分:1)

我同意之前的回答,建议在这种情况下使用.equals。但是,还有另一种简化此代码的技术。如果您希望使用List对象轻松实现数组,并且所有List实现都支持这些数组,则可以使用Arrays.asList获取数组的List视图:

import java.util.Arrays;
public class Test {
  public static void main(String[] args) {
    String [] secretWord={"S","W","I","N","G"};
    String [] content = new String[5];
    System.out.println(Arrays.asList(secretWord).equals(Arrays.asList(content)));
    content[0] = "S";
    content[1] = "W";
    content[2] = "I";
    content[3] = "N";
    content[4] = "G";
    System.out.println(Arrays.asList(secretWord).equals(Arrays.asList(content)));    
  }
}