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

我是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());
    }
}
}
hf51963051 回答:如何在Android Studio中创建分数计数器?

不要在方法中声明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);
   }

if 条件观察语句。在 if 内部,您正在创建得分变量,因此每次用户获得正确答案时,都会创建得分变量并将其递增,因此即使获得相同的组合多次,您也将始终获得1作为输出

因此,请了解该变量的作用域

本文链接:https://www.f2er.com/3144397.html

大家都在问