如何在Android Studio中创建分数计数器



我是安卓工作室的新手,对Java有基本的经验。我试图创建一个android应用程序,用户必须输入一个数字,一旦点击按钮,就会从0-6生成一个随机数字,如果输入的数字和生成的数字相同,则用户获得1分。我试着实现了一个分数计数器,但在正确猜测1次后,分数保持在1,再也不会增加了。

public class MainActivity extends AppCompatActivity {
String matchingnumbers = "Congratulations!";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void on_button_click(View view) {
TextView numberW = this.findViewById(R.id.textView);
EditText tvW = this.findViewById(R.id.editText);
TextView scoreW =this.findViewById(R.id.textView3);
Random r = new Random();
int dicenumber = r.nextInt(6);
numberW.setText(Integer.toString(dicenumber));
try {
int number = Integer.parseInt(numberW.getText().toString());
int tv = Integer.parseInt(tvW.getText().toString());
if(number==tv){
int score = 0;
score++;
Toast.makeText(getApplicationContext(), matchingnumbers, Toast.LENGTH_LONG).show();
scoreW.setText("Your score is = " + score);
}
}
catch (Exception ex) {
Log.e("Button Errors", ex.toString());
}
}
}

不要在方法中声明score,因为它不会保留。改为在类中声明:

public class MainActivity extends AppCompatActivity {
String matchingnumbers = "Congratulations!"; 
//here
int score = 0;
// ...
}

您编写的代码是。。。。

if(number==tv)
{
int score = 0;
score++;
Toast.makeText(getApplicationContext(), matchingnumbers, Toast.LENGTH_LONG).show();
scoreW.setText("Your score is = " + score);
}

如果条件,请遵守中的语句。在内部,如果您正在创建分数变量,因此每次用户得到正确答案时,分数变量都会被创建并递增,因此即使多次获得相同的组合,您也将始终获得1作为输出

因此,请理解该变量的范围

最新更新