0

How would I initialize an Array within an object who's length is that of a user's input? I want to set the number of bats via user input, and make that the array length, then within the array of basesAchieved, I want to set a number based on user input (1-4) representing the base achieved.

// set up a Batter
public class Batter
{
    private String batterName;
    private int numberOfBats;
    private int[] basesAchieved;

    // fill fields with empty data, how is this done with an array??
    public Batter()
    {
        this("", 0,0);
    }

    //
    public Batter(String batterName, int numberOfBats, int[] basesAchieved)
    {
        this.batterName = batterName;
        this.numberOfBats = numberOfBats;
        this.basesAchieved = basesAchieved;
    }

    public void setBatterName(String batterName)
    {
        this.batterName = batterName;
    }

    public String getBatterName()
    {
        return batterName;
    }

    public void setNumberOfBats(int numberOfBats)
    {
        this.numberOfBats = numberOfBats;
    }

    public int getNumberOfBats()
    {
        return numberOfBats;
    }

    // want to set an array to get a number (1-4) for each number of @ bats     
    // (numberOfBats). 
    public void setBasesAchieved(int[] basesAchieved)
    {
        this.basesAchieved = ;
    }

    public int getBasesAchieved()
    {
        return basesAchieved;
    }
}
Peter Hall
  • 53,120
  • 14
  • 139
  • 204
D. Guitner
  • 17
  • 1

2 Answers2

0

In the setter method you should assign this.basesAchieved = basesAchieved;. If you want to initialize the basesAchieved with a length then just: int[] basesAchieved = new int[yourlength] in the class you initialize Batter class, then call the setter method of this class

TuyenNTA
  • 1,194
  • 1
  • 11
  • 19
0

You have some errors in your class where you try to use an int array.

public Batter()
{
    this("", 0, new int[0]);
}

// skipped...

public void setBasesAchieved(int[] basesAchieved)
{
    this.basesAchieved = basesAchieved;
}

public int[] getBasesAchieved()
{
    return basesAchieved;
}

This question explains how to get user input How can I get the user input in Java?

One of the simplest ways is to use a Scanner object as follows:

Scanner reader = new Scanner(System.in);  // Reading from System.in
System.out.println("Enter a number: ");
int n = reader.nextInt(); // Scans the next token of the input as an int.

You can use this method to read the number of numberOfBats and create your object with the right array length. Then you can keep asking the user for input and put those into the basesAchieved array. Or you can ask the reader for all inputs first and then create your object.

Community
  • 1
  • 1
tima
  • 1,498
  • 4
  • 20
  • 28