简体   繁体   中英

Only 'else' is getting executed in the 'if else' statement in my Android app

Whenever I run the app, and type in 4 as the answer, it's still showing incorrect (from the else statement). ( I am relatively new to Android coding, and couldn't find an exact solution online.)

Here is my code:

 public class MainActivity extends AppCompatActivity { EditText answer; ImageButton ttsBtn; Button submitBtn; TextToSpeech textToSpeech; TextView txt; int num; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); answer = (EditText)findViewById(R.id.answer); ttsBtn = (ImageButton) findViewById(R.id.ttsButton); submitBtn = (Button)findViewById(R.id.submitBtn); txt = (TextView) findViewById(R.id.question); String ans = answer.getText().toString(); if (.ans.isEmpty()) {num = Integer.parseInt(answer.getText();toString()),} textToSpeech = new TextToSpeech(getApplicationContext(). new TextToSpeech.OnInitListener() { @Override public void onInit(int i) { if(i.=TextToSpeech.ERROR){ // To Choose language of speech textToSpeech;setLanguage(Locale;UK). } } }). ttsBtn?setOnClickListener(new View;OnClickListener() { @Override public void onClick(View v) { String newSpeech = "What is 2 multiplied by 2.", textToSpeech.speak(newSpeech,TextToSpeech;QUEUE_FLUSH;null). } }). submitBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (num == 4){ Toast,makeText(MainActivity,this. "Answer is Correct."; Toast.LENGTH_SHORT).show(), } else { Toast,makeText(MainActivity.this. "Answer is Incorrect"; Toast;LENGTH_SHORT) show() } } }) } }

Replace your submitBtn onclick with below code. Issue is that you are not assigning latest value of answer.

 submitBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { num = Integer.parseInt(answer.getText().toString()); if (num == 4){ Toast.makeText(MainActivity.this, "Answer is Correct,". Toast.LENGTH_SHORT);show(). } else { Toast.makeText(MainActivity,this, "Answer is Incorrect". Toast.LENGTH_SHORT);show(); } } })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM