我在Android应用程序上使用的函数有点问题。 功能不是太难,它只是一个带有两个随机整数的简单计算。 问题是我有一个标签,我想将文本更改为“问题”,以便用户可以解决它。我知道这个功能有问题,但我无法弄清楚是什么。我最接近的猜测是返回部分是错误的(因为它是空的),但到目前为止我无法解决它。
这是我的代码:
import java.util.Random;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class Game extends Activity implements OnClickListener {
private static final String TAG = "Game";
int game[];
public static final String KEY_DIFFICULTY = "com.example.coursework1.dificulty";
public static final int DIFFICULTY_NOVICE = 0;
public static final int DIFFICULTY_EASY = 1;
public static final int DIFFICULTY_MEDIUM = 2;
public static final int DIFFICULTY_GURU = 3;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
int diff = getIntent().getIntExtra(KEY_DIFFICULTY, DIFFICULTY_NOVICE);
game = getGame(diff);
}
public int[] getGame(int diff) {
// TODO Auto-generated method stub
String operators [] = {"+","-","*","/"};
Random op1, op2, op3, op4, op5, op6;
if(diff == getIntent().getIntExtra(KEY_DIFFICULTY, DIFFICULTY_NOVICE)){
op1 = new Random();
op2 = new Random();
int operator = new Random().nextInt(operators.length);
String random = (operators[operator]);
int generate1 = op1.nextInt(10);
int generate2 = op2.nextInt(10);
int operation;
if(random == "+"){
operation = generate1 + generate2;
TextView setProblemToView = (TextView) findViewById(R.id.problem);
setProblemToView.setText("generate1" + random + "generate2");
}
}
return null;
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
答案 0 :(得分:0)
为什么在必须返回时使用int ruturn总是为null?像这样使用它:
public void getGame(int diff) {
String operators [] = {"+","-","*","/"};
Random op1, op2, op3, op4, op5, op6;
if(diff == getIntent().getIntExtra(KEY_DIFFICULTY, DIFFICULTY_NOVICE)){
op1 = new Random();
int operator = new Random().nextInt(operators.length);
String random = (operators[operator]);
int generate1 = op1.nextInt(10);
int generate2 = op1.nextInt(10);
int operation;
if( "+".equalsIgnoreCase(random) ){
operation = generate1 + generate2;
TextView setProblemToView = (TextView) findViewById(R.id.problem);
setProblemToView.setText("generate1" + random + "generate2");
}
}
}
并将其称为:
getGame(diff);
我的修改中解决了相同的随机问题,请查看that了解更多