因此,从本质上来讲,我在这里的这个程序有问题,应该让一个老师使用参差不齐的数组输入要输入分数的学生数量,然后为每个学生输入多少测试分数。不幸的是,我的数组不允许任何学生获得不同数量的分数。我真的不确定我做错了什么。
`import 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();
} }`
答案 0 :(得分:3)
首先,不要预先声明局部变量。通常,应该在(首次)分配它们的地方声明它们。
如果这样做,通常会在代码块内声明局部变量,即局部变量的作用域是该代码块,并且在该块结束时不再可用。这将为您提供帮助,因为当您使用不再相关的变量值时,编译器现在可以告诉您(错误消息)。
就像您的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;
}
}
您需要再做一次,您的代码应该很好(无论如何,在衣衫agged的部分)。
答案 1 :(得分:0)
有一个非常简单的方法。您只需要访问每个学生的分数,即可通过以下方式进行操作:
for(int i = 0; i < num; i++)
{
count++;
for(int j = 0; j < ragged[i].length; j++)
{
System.out.println("Student #"+ count + "'s " + (j + 1) + "'st score is: " );
each = kbd.nextInt();
ragged[i][j] = each;
}
}
第ragged[i].length
行将分别访问每个数组中的元素数量,然后您可以为每个学生获得不同数量的分数