0

so i have a private String[] teamName;. all i want to do is simply use a String output by a user and store that String into String[] teamName;. I am taking teamName[team] and equaling it to = keyboard.nextLine(), doing this is giving me a nullexpection error. why?

so for this is what i have ...

private String[] teamName; // contains an entry for each team

public void enterInData( )
{
    Scanner keyboard = new Scanner(System.in);

    System.out.println("Enter number of teams:");
    numberOfTeams = keyboard.nextInt( );

    System.out.println("Enter number of weeks:");
    numberOfWeeks = keyboard.nextInt( );

    scores =new int [numberOfTeams][numberOfWeeks];
    // ************** Fill in Code ***************
    // Allocate array memory for teamName to store the team names.
    // Allocate array memory for scores (2 dimensional array) to store a 
    // score for each team for each week. 
        teamName = new String[4];
    for (int team = 0; team < numberOfTeams; team++)
    {
        System.out.println("Enter team name");

        // ************* Fill in Code **************
        // Read in Team name and store it in teamName
        teamName = new String[team];
        teamName[team] =  keyboard.nextLine();



        for (int week = 0; week < numberOfWeeks; week++)
        {
            System.out.println("Enter score for team "+ teamName[team]);
            System.out.println("on week number " + (week+1));
            // ************  Fill in Code ***************
            // Read in a score and store it in the proper spot in the scores array
         scores[team][week] = keyboard.nextInt();
         }

}

2 Answers 2

1

You get an null pointer exception because when you are re-declaring the stringTeam array within the loop (not needed at all) you are using the variable team as the size of the array. At the first iteration of the loop that variable has value 0. You create an empty array with 0 dimensions. What you want is simply to assign a String:

teamName[team] = keyboard.nextLine();
Sign up to request clarification or add additional context in comments.

Comments

0

The line teamName = new String[team]; inside your for loop resets the whole array to be full of nulls. You're erasing everything you already had.

2 Comments

so how can i allocated Array memory for teamName to store team names.
Deleting that line would be a start. You already allocated the array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.