2013-03-15 119 views
0

我有一個字符串"sss"和一個字符數組{'s','s','s'}。我將該數組轉換爲字符串,但消息「兩者相等」在比較它們時未打印。爲什麼?如何在android中比較字符串和字符數組?

public class RoughActivity extends Activity 
{ 
private Button checkButton; 
private TextView text; 

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
     start(); 
     } 

     private void start() { 
      int i; 
      checkButton=(Button)findViewById(R.id.go); 
      text=(TextView)findViewById(R.id.display); 
      final String question="sss"; 
      final char answer[]=new char[question.length()]; 
      for(i=0;i<question.length();i++) 
      { 
       answer[i]='s'; 
      } 
      checkButton.setOnClickListener(new View.OnClickListener(){ //on clicking the button,the text must be filled with "both are equal" 
       public void onClick(View v){ 
        if(question.equals(answer)) 
        { 
         text.setText("both are equal"); 
        } 


       }}); 
} 
} 
+1

你試圖比較一個字符串與一個字符數組是兩個非常不同的東西.. – 2013-03-15 14:58:34

回答

5

從字符數組中創建一個新字符串並進行比較。

If(question.equals(new String(answer)){ 
} 

If(question.equals(answer.toString()){ 
} 

話雖如此,我無法想象,爲什麼你想存儲的char []的答案。

1
public boolean equals (Object object) 

該方法將指定的對象與此字符串進行比較,如果它們相等則返回true。該對象必須是具有相同順序的相同字符的字符串實例。

所以首先你需要先使用toString方法將它轉換爲第一個字符串。

對於前:

String string = charArray.toString(); 
0

你可以使用一個循環。

boolean equal = true; 
for (int i = 0; i < answer.length; i++) { 
     if (!question.charAt(i) == answer[i] { 
      equal = false; 
      break; 
     } 
} 

我認爲應該有效。