2016-04-12 16 views
0

私はプライベートString [] teamName;を持っています。私がやりたいことは、単にユーザーがString出力を使用し、そのStringをString [] teamName;に格納することです。 私はteamName [team]を取って、それを= keyboard.nextLine()と同じにしています。これは、nullexpectionエラーを出しています。どうして?したがって、このためどのようにユーザーの文字列出力をString []配列に格納することができます

は...私が持っているものである

プライベートString []型TEAMNAME。 //は、配列全体がヌルでいっぱいであることをリセットしあなたforループ内の各チームのエントリー

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(); 
     } 

}

答えて

0

ラインteamName = new String[team];が含まれています。あなたはすでに持っているものすべてを消しています。

+0

チーム名を格納するためにteamNameの配列メモリを割り当てるにはどうすればよいですか。 –

+0

その行を削除することが開始です。すでに配列を割り当てています。 –

1

ループの中でstringTeam配列を再宣言しているとき(変数は必要ありません)、変数teamを配列のサイズとして使用しているため、NULLポインタ例外が発生します。ループの最初の反復で、変数の値が0になります。0次元の空の配列を作成します。 単に文字列を割り当てるだけです:

teamName[team] = keyboard.nextLine(); 
関連する問題