Reputation: 75
I have a game with progress chart and an array. I want to have a chart which the player can see its score in its last 5 games.
here's my code in my array
int[] Addition = { score1, score2, score3, score4, score5 };
if (score1 == 0) {
score1 = Game.score;
} else if (score1 != 0 && score2 == 0) {
score2 = 21;
} else if (score2 != 0 && score3 == 0) {
score3 = Game.score;
} else if (score3 != 0 && score4 == 0) {
score4 = Game.score;
} else if (score4 != 0 && score5 == 0) {
score5 = Game.score;
}
What is the problem on my logic? when it runs my first game score seems to be right. but when i play one more its just that the 1st element of the array is changing? where Am I wrong? btw please apologize my english. and I appreciate any suggestions and comments. thanks guys
:::UPDATE:::
here's my code now. Can someone check if my initialization is correct:
public class ProgressGraph extends Activity {
int[] Addition = { 0, 0, 0, 0, 0 };
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
openChart();
}
public void openChart() {
for (int i = 0; i < 5; i++) {
if (Addition[i] == 0) {
Addition[i] = Game.score;
break;
}
}
Upvotes: 2
Views: 86
Reputation: 1392
Taking into account your update.
- When you declare the array. The variable has a capital letter so it may have a conflict with a class. Replace Addition
by addition
.
With this code, if you start another activity, scores will be reset. You have to use Application extended class or SharedPreferences to save scores.
Upvotes: 0
Reputation: 312
Are you trying to move each old score down the list?
for (int i = 4; i > 0; i--) {
Addition[i] = Addition[i-1];
}
Addition[0] = Game.score;
In these code samples we've provided, the array values should be initialized to zero:
int[] Addition = { 0, 0, 0, 0, 0};
Upvotes: 2
Reputation: 366
I would do something like this:
for(int i = Addition.length-1; i > 0; i--){
Addition[i] = Addition[i-1];
}
Addition[0] = Game.score;
This will mean that the most recent game will always be in position 0. If the user plays more than 5 games the oldest score gets replaced.
It also allows the user to be able to score 0.
Upvotes: 3
Reputation: 1392
This part of code seems to be good. I think your score array is reset when you start the second game. Did you try to print the scores array before the end of the second game ? Does the first score remain stored ?
Then I suggest you to use a loop like that (not tested):
for (int i = 0; i < 5; i++) {
if (score[i] == 0) {
score[i] = Game.score;
break;
}
}
Upvotes: 3