我尝试使用JScript在Android Studio上创建随机数生成器。该应用程序可以正常工作,但是当用户输入任何内容时它会崩溃,并且在用户重新启动应用程序之前它也不会更改随机数。 我尝试过以下代码:
public class MainActivity extends AppCompatActivity {
int randomNumber;
public void checkGuess(View view){
EditText guessedNumber = (EditText) findViewById(R.id.guessedNumber);
String guessedNumberString = guessedNumber.getText().toString();
int guessedNumberInt = Integer.parseInt(guessedNumberString);
String message = "";
if (guessedNumberInt>randomNumber){
message = "Too large!";
}else if(guessedNumberInt<randomNumber){
message = "Too small!";
}else {
message = "correct!";
}
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Random randomGenerator = new Random();
int randomNumber = randomGenerator.nextInt(21);
}
}
当用户猜对时,我应该怎么做才能更改随机数,以及当用户什么都不输入时如何修复应用程序崩溃?
答案 0 :(得分:0)
使随机randomGenerator全局化。问题是你只生成一次随机数.onCreate只会被调用。你需要在每次调用时创建一个随机数。
像这样更改onCreate
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
randomGenerator = new Random();
}
}
然后像这样改变你的checkGuess方法
public void checkGuess(View view){
int randomNumber = randomGenerator.nextInt(21);
EditText guessedNumber = (EditText) findViewById(R.id.guessedNumber);
String guessedNumberString = guessedNumber.getText().toString();
if(TextUtils.isEmpty(guessedNumberString)){
Toast.makeText(getApplicationContext(), "Please enter a number", Toast.LENGTH_LONG).show();
return;
}
int guessedNumberInt = Integer.parseInt(guessedNumberString);
String message = "";
if (guessedNumberInt>randomNumber){
message = "Too large!";
}else if(guessedNumberInt<randomNumber){
message = "Too small!";
}else {
message = "correct!";
}
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
答案 1 :(得分:0)
这里用它来解决你的问题:
public void checkGuess(View view){
EditText guessedNumber = (EditText) findViewById(R.id.guessedNumber);
String guessedNumberString = guessedNumber.getText().toString();
String message = "";
int guessedNumberInt =0;
if (guessedNumberString.length() > 0){
Random randomGenerator = new Random();
int randomNumber = randomGenerator.nextInt(21);
guessedNumberInt = Integer.parseInt(guessedNumberString);
if (guessedNumberInt>randomNumber){
message = "Too large!";
}else if(guessedNumberInt<randomNumber){
message = "Too small!";
}else {
message = "correct!";
}
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
}else{
//show message to enter a value
}
}