此程序应采用用户定义的数字,创建该大小的数组,并让用户使用do..while循环输入元素 - 即成绩。然后,程序需要显示从最低到最高输入的所有成绩,累积成绩,并找到平均值。
我的输出没有正确显示输入的成绩(如果我输入10,20,30,它显示00,10,20)我无法弄清楚我做错了什么。有什么帮助吗?
import java.util.Arrays;
import java.util.Scanner;
public class LoopArray
{
public static void main(String[] arg)
{
Scanner keyboard = new Scanner(System.in);
int count = 0;
double totalAverage = 0;
double gradesTotal = 0;
System.out.println("Please input the number of grades you would like to submit for an average: ");
int numberOfGrades = keyboard.nextInt();
int[] studentScores = new int[numberOfGrades];
do
{
System.out.println("Please enter grade for averaging: ");
int inputGrade = keyboard.nextInt();
count++;
gradesTotal += inputGrade;
} while (count < numberOfGrades);
Arrays.sort(studentScores);
for(count=0; count < studentScores.length; count++)
{
System.out.println("Grades entered were: " + count + studentScores[count]);
}
totalAverage = gradesTotal / numberOfGrades;
System.out.println("The total of all grades entered is: " + gradesTotal);
System.out.println("The average of grades entered is: " + totalAverage);
}
}
答案 0 :(得分:1)
结果
Grades entered were: 00
Grades entered were: 10
Grades entered were: 20
是用
生成的System.out.println("Grades entered were: " + count + studentScores[count]);
因此,每行中的最后一个数字是代表count
+ studentScores[count]
的对。这意味着:
00
- &gt;位置0
数组studentScores
存储0
。 10
- &gt;位置1
数组studentScores
存储0
20
- &gt;位置2
数组studentScores
存储0
这意味着您没有使用用户的值填充studentScores
数组。
答案 1 :(得分:0)
因为count
从0开始。你应该检查它。
答案 2 :(得分:0)
您没有在数组中添加任何值。你需要将它添加到循环studentScores[count] = inputGrade;
的部分中
现在,您的do while
循环应如下所示:
do
{
System.out.println("Please enter grade for averaging: ");
int inputGrade = keyboard.nextInt();
studentScores[count] = inputGrade;
count++;
gradesTotal += inputGrade;
} while (count < numberOfGrades);
此外,在上一个for-loop
内,您正在打印额外信息。只需从System.out.println
System.out.println("Grades entered were: " + studentScores[count]);
你不明白的任何事情让我知道谢谢
答案 3 :(得分:0)
您忘记使用输入的花园填充数组
do
{
System.out.println("Please enter grade for averaging: ");
int inputGrade = keyboard.nextInt();
studentScores[count]=inputGrade;
count++;
gradesTotal += inputGrade;
} while (count < numberOfGrades);