ak_27
ak_27

Reputation: 27

How to keep track of high score in java?

The purpose of the Java program is to pick a random integer between 0 and 11 inclusive every time you press a button. If the integer is 1 or 2 then the total is 0. otherwise the integer is added to the running total. I've done all that but I can't figure out how to update the high score (it's supposed to update whenever a higher score is achieved).

public void update() { 
  int value = ((int)(Math.random() * (11 - 1 + 1) + 1)); 
  label1.setText("Value: " + value); 

  if (value < 3) { 
    total = 0; 
  } else {
    total = value + total;
  }

  label2.setText("Total: " + total); 

  if (highScore <= total) { 
    label3.setText("High Score: " + highScore); 
  }
}

But I know the last part won't work because I haven't done anything with the variable highScore.

Upvotes: 1

Views: 2517

Answers (4)

John G
John G

Reputation: 98

First, you need to declare highScore OUTSIDE of the update method. highScore will be thrown away when you exit the method and created again when you enter the update method, so it'll always be what you initially initialize it to. You have to initialize highScore to a minimum value that you won't encounter in your program. Your best bet is to use Integer.MIN_VALUE.

int highScore = Integer.MIN_VALUE;

public void update()
{
    ...
}

Next, you need to test if the total is higher than highScore. If the total is higher, then update highScore to the total. NOTE: using < or <= is up to you, it won't change the highScore. It depends on if you are determining who last reached the high score (which it doesn't look like you are doing), so using < won't perform unneeded operations.

if (highScore < total) {
    label3.setText("High Score: " + highScore);
    highScore = total;
}

Upvotes: 0

Msp
Msp

Reputation: 2493

You must initialise highScore = 0 while declaring. Then after getting a highScore you should update the value of highScore with new value.

Try this,

public void update() {

    int value = ((int) (Math.random() * 11 + 1));
    label1.setText("Value: " + value);

    if (value < 3) {
        total = 0;
    } else
        total = value + total;

    label2.setText("Total: " + total);

    if (highScore < total) {
        highScore = total;
        label3.setText("High Score: " + highScore);
    }
}

Upvotes: 2

Eric G
Eric G

Reputation: 926

Set highScore = 0; whereever you first declare it.

Then add this line to the if statement

if (highScore <= total) {
    label3.setText("High Score: " + highScore);
    highScore = total;
}

Upvotes: 1

Steve Cohen
Steve Cohen

Reputation: 4859

if(highScore < total) 
 { 
  highScore = total;
  label3.setText("High Score: " + highScore); 
 } 

Note, I think you want < rather than <=

Upvotes: 2

Related Questions