在我的游戏中,我有一个哈希按钮,就像一个提交按钮。当我按下哈希按钮它显示INCORRECT即使答案是正确的,我是否必须为数组中的每个位置添加不同的if语句?它显示INCORRECT每个表达式。
(抱歉,我是新手)
package com.gamesup.braingame;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Easy extends Activity implements OnClickListener{
EditText display;
// This Array says , I am an array that holds arrays
String [][] multiArray = {{"4 + 5", "9"},
{"20 * 3","60"},
{"99 - 9","90"}};
TextView displayExpression;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.easy);
display = (EditText)findViewById(R.id.displayText);
display.setText("?");
displayExpression = (TextView) findViewById(R.id.expression);
Button generate = (Button) findViewById(R.id.random_gen);
generate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Random ranGenerate = new Random ();
int random = ranGenerate.nextInt(multiArray.length) ;
// Fetch your random question
String Rquestion = multiArray[random][0];
displayExpression.setText(Rquestion);
}
});
}
static boolean isEmpty = true;
public void num_Clicked(View v){
Button btn = (Button) findViewById(v.getId());
//getting the button object and using a view to get the id of the buttons
if (v.getId()== R.id.del_button){
String s = display.getText().toString();
s = s.substring(0, s.length() - 1);
display.setText(s);
return;
}
if(isEmpty){
display.setText(btn.getText());
isEmpty = false;
}
else{
display.append(btn.getText().toString());
}
public void hash_Clicked(View v){
if (v.getId()== R.id.hash_button){
// Get the Answer from your EditText
String answer = display.getText().toString();
// Using a for loop iterate on the base index
for(int i = 0; i < multiArray.length ; i++)
{
// if the answer is in position 1 of Array [i]
if(answer.equals(multiArray[i][1]))
{
// We have found the answer, Congratulate the User
displayExpression.setText("CORRECT");
}else{
// Tell them how bad they are since they can't solve simple equations!
displayExpression.setText("INCORRECT");
}
}
}
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
答案 0 :(得分:0)
在您显示答案是正确的之后放置break
语句,这样您就不会遍历数组中的剩余答案并与当前进行比较,因为如果您在索引0处有正确的答案,你仍然会在数组中查看剩下的答案,所以你的“正确”会被“不正确”所取代。
// if the answer is in position 1 of Array [i]
if(answer.equals(multiArray[i][1]))
{
// We have found the answer, Congratulate the User
displayExpression.setText("CORRECT");
break; //<---add this to exit the loop, because correct answer has been found
}