所以基本上我在这里遇到这个程序的问题应该让老师输入他们想要为多少学生输入分数,然后为每个学生输入多少考试分数 - 使用参差不齐的数组。不幸的是,我的数组不允许任何学生有不同数量的分数。我真的不确定我做错了什么。
`导入java.util.Scanner;
public class part2
{
public static void main (String[] args)
{
//Declarations
int num;
int count = 0;
int scores = 0;
int sum = 0;
double average = 0;
int check = 1;
int each = 0;
//Open new scanner
Scanner kbd = new Scanner (System.in);
//Get number of students
System.out.println("Please enter how many students you would like to enter scores for: ");
num = kbd.nextInt();
//Create ragged array
int[][] ragged = new int[num][];
//Get number of scores for each student
for(int i = 0; i < num; i++)
{
count++;
System.out.println("For student #" + count + " how many scores do you have? ");
scores = kbd.nextInt();
ragged[i] = new int[scores];
}
count = 0;
//Get each student's score
for(int i = 0; i < num; i++)
{
count++;
for(int j = 0; j < scores; j++)
{
System.out.println("Student #"+ count + "'s " + (j + 1) + "'st score is: " );
each = kbd.nextInt();
ragged[i][j] = each;
}
}
//Get each student's average of scores
for(int i = 0; i < num; i++)
{
check++;
for(int j = 0; j < scores; j++)
{
sum += ragged[i][j];
average = ((double)sum / (double)scores);
}
System.out.println("The Average for student #" + (check - 1) + " is: " + average);
}
//Housekeeping
kbd.close();
} }`
最佳答案
首先,不要预先声明局部变量。您通常应该在(首先)分配它们的地方声明它们。
如果这样做,局部变量通常会在代码块内声明,即局部变量的范围仅限于该 block ,并且在 block 结束时不再可用。这会对您有所帮助,因为编译器现在可以在您使用不再相关的变量值时告诉您(错误消息)。
就像您的 scores
变量一样。它在循环内赋值,在循环结束后,它将具有last 值,即对其余代码完全无用的值。
因此,在循环内移动声明:
//Get number of scores for each student
for(int i = 0; i < num; i++)
{
count++;
System.out.println("For student #" + count + " how many scores do you have? ");
int scores = kbd.nextInt(); // <=== Declare it here
ragged[i] = new int[scores];
}
现在您会在错误地尝试使用它的地方遇到编译错误。那是因为在那些地方你需要获得与相关行相关的值。如果你愿意,你可以在那里重新声明和初始化变量:
count = 0;
//Get each student's score
for(int i = 0; i < num; i++)
{
count++;
int scores = ragged[i].length; // <=== Re-declare and initialize here
for(int j = 0; j < scores; j++)
{
System.out.println("Student #"+ count + "'s " + (j + 1) + "'st score is: " );
each = kbd.nextInt();
ragged[i][j] = each;
}
}
你需要再做一次,你的代码应该是好的(无论如何在破烂的部分)。
关于java - 参差不齐的数组不允许我有不同的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55839335/