我是android studio的初学者.我正在开发一个测验应用程序.应用程序应检查要比较的两个字符串并给出正确的答案.但比较两个字符串(即使它们是相同的)并没有给出正确的输出.相反,它直接转到代码中的最终return语句.这是代码:
// ... EditText Answer1 = (EditText) findViewById(R.id.answer1); String ans = Answer1.getText().toString(); Log.v("MainActivity", "City name :" + ans); String answer= String.valueOf(Answer1); // ... public String YourAnswers(String ans, boolean isDT, boolean isHC, boolean isBO,String answer) { String Message = "1.:You answered \n"+ans+ "\n" +ques1(answer); Message = Message + " \n 2.: \n" +question2(isDT,isHC,isBO) ; return Message; } public String ques1(String answer) { if (answer == "Jefferson City"){//||ans=="Jeff City"||ans=="Jeffcity"||ans=="Jeffersoncity"){ return "correct"; } else if(answer =="Jeff City") { return "correct."; } else if(answer =="Jeffcity"){ return "correct.."; } else if(answer.equals("Jeffersoncity")){ return "correct....."; } return "Sorry,but the correct ans is Jefferson City"; }
当它进入时ques1()
,它直接进入最后一个声明即return "Sorry,but the correct ans is Jefferson City";
.当我输入正确的答案时,它返回上面提到的行.
关于为什么会发生这种情况的任何想法?
"=="不是比较java中String的内容的正确方法.
使用string1.equals(string2)