如何将用户String输出存储到String []数组中

时间:2016-04-12 22:47:18

标签: java arrays string

所以我有一个私人String [] teamName;。我想要做的只是使用用户输出的String并将该String存储到String [] teamName;中。 我正在使用teamName [team]并将其等于= keyboard.nextLine(),这样做会给我一个nullexpection错误。为什么呢?

所以这就是我的......

private String [] teamName; //包含每个团队的条目

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 个答案:

答案 0 :(得分:1)

你得到一个空指针异常,因为当你在循环中重新声明stringTeam数组时(根本不需要),你使用变量team作为数组的大小。在循环的第一次迭代中,变量的值为0.您创建一个0维的空数组。 你想要的只是分配一个字符串:

teamName[team] = keyboard.nextLine();

答案 1 :(得分:0)

teamName = new String[team];循环中的行for会重置整个数组以充满空值。你正在删除你已经拥有的一切。