简体   繁体   中英

How do I create a score counter in Android Studio?

I'm a complete newbie to Android Studio and have basic experience in Java. I tried to create an android app where the user has to input a number, once the button is clicked a random number is generated from 0-6, if the input number and the generated number is the same then the user gains 1 point. I've tried to implement a score counter but after 1 correct guess the score stays at 1 and never increases any further.

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());
    }
}
}

Don't declare score in the method, because it does not remain. Declare it in the class instead:

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

The Code you have written is this....

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

Observe the statements in if condition. Inside the if you are creating score variable so each time the user gets the correct answer the score variable will be created and its incremented so you will get always 1 as output even you get the same combination so many times

So, understand the scope of that variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM