Book Image

Learning Java by Building Android Games

By : John Horton
Book Image

Learning Java by Building Android Games

By: John Horton

Overview of this book

Table of Contents (17 chapters)
Learning Java by Building Android Games
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Java arrays – an array of variables


You might be wondering what happens when we have a game with lots of variables to keep track of. How about a table of high scores with the top 100 scores? We could declare and initialize 100 separate variables like this:

int topScore1;
int topScore2;
int topScore3;
//96 more lines like the above
int topScore100;

Straightaway, this can seem unwieldy, and what about the case when someone gets a new top score and we have to shift the scores in every variable down one place? A nightmare begins:

topScore100 = topScore99;
topScore99 = topScore98;
topScore98 = topScore97;
//96 more lines like the above
topScore1 = score;

There must be a better way to update the scores. When we have a large set of variables, what we need is a Java array. An array is a reference variable that holds up to a fixed maximum number of elements. Each element is a variable with a consistent type.

The following line of code declares an array that can hold int type variables, even a high score...