gpt4 book ai didi

java - 如何将用户字符串输出存储到 String[] 数组中

转载 作者:行者123 更新时间:2023-12-01 10:04:04 24 4
gpt4 key购买 nike

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

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

私有(private)字符串[]团队名称;//包含每个团队的条目

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

}

最佳答案

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

teamName[team] = keyboard.nextLine();

关于java - 如何将用户字符串输出存储到 String[] 数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36585445/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com