import java.util.Scanner;
public class Average
{
public static void main(String[] args)
{
int mark;
int countTotal = 0; // to count the number of entered marks
int avg = 0; // to calculate the total average
Scanner Scan = new Scanner(System.in);
System.out.print("Enter your marks: ");
String Name = Scan.next();
while (Scan.hasNextInt())
{
mark = Scan.nextInt();
countTotal++;
avg = avg + ((mark - avg) / countTotal);
}
System.out.print( Name + " " + avg );
}
}
Scanner scores = new Scanner(stdin.nextLine());扫描包含分数的行
另请注意,它使用更简单且更易读的公式来计算平均值。
Scanner stdin = new Scanner(System.in);
System.out.print("Enter your average: ");
String name = stdin.next();
int count = 0;
int sum = 0;
Scanner scores = new Scanner(stdin.nextLine());
while (scores.hasNextInt()) {
sum += scores.nextInt();
count++;
}
double avg = 1D * sum / count;
System.out.print(name + " " + avg);