我在这里很新,我正在关注Udemy的这个课程,Udemy正在制作一个名为“更高或更低”的项目。我写了这段代码,我不断收到这个错误,上面写着:
error: Cannot find symbol variable rand
这是我的代码:
package com.harimahmed.higherorlower;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
int randomNumber;
public void guess(View view) {
EditText guessEditText = (EditText) findViewById(R.id.guessEditText);
int guessInt = Integer.parseInt(guessEditText.getText().toString());
if (guessInt > randomNumber) {
Toast.makeText(this, "Lower!", Toast.LENGTH_SHORT).show();
} else if (guessInt < randomNumber) {
Toast.makeText(this, "Higher!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "That's it! Play again!", Toast.LENGTH_SHORT).show();
randomNumber = rand.nextInt(20) + 1;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Random rand = new Random();
randomNumber = rand.nextInt(20) + 1;
}
谢谢!
你可以将rand
作为全局变量。
1.在private Random rand;
方法之外使用onCreate()
2.您可以在rand = new Random();
方法中初始化数据onCreate()
。
然后你可以在另一个地方打电话。
试试
private Random rand;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rand = new Random();
randomNumber = rand.nextInt(20) + 1;
}