我正在尝试计算学生成绩的平均值:
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 );
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个使用两个的解决方案Scanner(如我之前的回答所示).
Scanner stdin = new Scanner(System.in); 扫描用户的输入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);
Run Code Online (Sandbox Code Playgroud)
样本输出:
Enter your average: Joe 1 2 3
Joe 2.0
Run Code Online (Sandbox Code Playgroud)