为什么我的代码没有打印到stdout?

编程入门 行业动态 更新时间:2024-10-14 00:26:33
本文介绍了为什么我的代码没有打印到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?

本文发布于:2023-10-27 10:52:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1533156.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:代码   stdout

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!