本文介绍了为什么我的代码没有打印到stdout?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算学生分数的平均值:

I'm trying to calculate the average of a student's marks:

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 的解决方案(如我的)。

Here's a solution that uses two Scanner (as suggested in my previous answer).


  • 扫描仪stdin =新扫描仪(System.in); 扫描用户输入

  • 扫描仪得分=新扫描仪( stdin.nextLine()); 扫描包含分数的行

  • Scanner stdin = new Scanner(System.in); scans user's input
  • Scanner scores = new Scanner(stdin.nextLine()); scans the line containing the scores

另请注意,它使用了很多用于计算平均值的更简单,更易读的公式。

Note also that it uses a much simpler and more readable formula for computing the average.

        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);

样本输出:

Enter your average: Joe 1 2 3
Joe  2.0

这篇关于为什么我的代码没有打印到stdout?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 07:46
查看更多