我創建了一個測驗活動,當用戶將他或她的答案輸入到EditText中並按下「Next」按鈕時,它將生成下一個隨機單詞並檢查您是否正確或錯誤。字符串比較不起作用
但是,由於某些原因,即使我的代碼能夠檢測到EditText和正確的單詞答案,它也會向我返回'錯誤答案'代碼。任何人都可以幫助我嗎?謝謝! (我還是這個新...)
* 編輯:這是不是一個重複的問題的人。我真的需要有人專門查看我的代碼,並確切告訴我什麼是錯誤的,因爲我不知道。這不是一個普遍的問題,無論如何,只要看看其他人的問題就可以解決,因爲我對此仍然很陌生。 。非常感謝*
btnNext.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
EditText etGuess= (EditText) findViewById(R.id.editTextGuess);
etguess2 = etGuess.getText().toString();
//these two above were actually placed outside but no luck. didnt work here either
String etg2str = etguess2; // the users edittext input
String tgstr = theguess; // the correct answer, the guess is from outside
if (myCD > 0 && etg2str.toString() == tgstr.toString()){
myCD--; //this is a countdown of the number of qns
Toast.makeText(getApplicationContext(), "correct answer"+ myCD + rantitle + " now",
Toast.LENGTH_LONG).show(); // this has nvr appeared for me
savePreferences("countDown", myCD);
RandomTitle(); //calling for random word on next load
Intent iNext = new Intent(QuizActivity.this,
QuizActivity.class);
iNext.putExtra("dataR", rantitle); //inputting random word for next load
startActivityForResult(iNext, 1);
finish();
}
else if (myCD > 0 && etg2str.toString() != tgstr.toString()){
myCD--;
Toast.makeText(getApplicationContext(), "wrong answer " + myCD + rantitle + etguess2 + theguess + " now",
Toast.LENGTH_LONG).show();
//now this one above appears for me everytime yet even tho etguess2 and theguess appears the same, I get wrong number
savePreferences("countDown", myCD);
RandomTitle();
Intent iNext = new Intent(QuizActivity.this,
QuizActivity.class);
iNext.putExtra("dataR", rantitle);
startActivityForResult(iNext, 1);
finish();
}
else{
Intent iScore = new Intent(QuizActivity.this,
ScoreActivity.class);
startActivityForResult(iScore, 1);
myCD = 10;
savePreferences("countDown", myCD);
finish();
}
}
});
}
見:http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java – pedromss
使用.equals()的字符串比較方法。 – Wajahat