kylclrk
kylclrk

Reputation: 3

How to dynamically create a specified number of arrays with different names in Java

I'm writing this golf program for my class that takes a .txt that has 5 numbers per row and 18 rows. The first number in each row is the par for that hole. The other four numbers are for each player.

I kind of have my own spin on this program, though. I wrote another program to create the .txt file with random numbers. The output is dependent on how many players there are which is inputted by the user.

Anyway, I've gotten the .txt generator just fine and I've gotten the Golf program to accurately count how many players there are. What I can't figure out is how to create that number of arrays with different names. I want each array to be int player1[18], player2[18], player3[18], etc.

Here's my code up to that point:

    import java.util.Scanner;
    import java.io.*;

public class Golf
{
    public static void main(String[] args) throws java.io.IOException
    {
        Scanner countScan = new Scanner(new File("golfscores.txt"));
        Scanner file = new Scanner(new File("golfscores.txt"));

    //------------------------------------------------------------
    // Counting the number of players
    //
    // This takes the number of integers in the file, divides it by
    // the 18 holes in the course and subtracts 1 for the par.
    //
    // I needed to count the players because it's a variable that
    // can change depending on how many players are entered in the
    // java program that creates a random scorecard.
    //------------------------------------------------------------
        int players = 0;

        for (int temp = 0; countScan.hasNextInt(); players++)
            temp = countScan.nextInt();
        players = players/18-1;

    //------------------------------------------------------------
    //Creating necessary arrays
    //------------------------------------------------------------



    }
}

EDIT: I must use an array for each player and I am not allowed to use ArrayLists. At this point it looks like I will be using an array of arrays as suggested by some in the comments. Didn't know this was a thing (obviously I'm very noob).

Upvotes: 0

Views: 73

Answers (2)

Mark
Mark

Reputation: 1498

Well you can use a HashMap to store your arrays. Or if you don't care about using strings to get to the array just use 2D Arrays like this:

int[][] players = new int[playerCount][18];

If you then use for example player 2 and want to see hole 12, you'd call players[1][11]

Upvotes: 1

Xvolks
Xvolks

Reputation: 2155

You should not go that way.

Instead create a class named Player to hold each player properties, then create a list of players: List<Player> players = new ArrayList<>();

Add each new player to that list.

Upvotes: 0

Related Questions