为什么我的代码没有向标准输出打印任何内容? [关闭]

2024-02-25

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

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(正如我的建议之前的回答 https://stackoverflow.com/questions/2753442/how-do-i-add-an-average-when-its-entered-from-user-input/2753468#2753468).

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

示例输出:

Enter your average: Joe 1 2 3
Joe  2.0
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么我的代码没有向标准输出打印任何内容? [关闭] 的相关文章

随机推荐