java - 如何使无效数字不添加到我的最终计算和计数器总计中?

标签 java

当我输入一个有非法分数提示的数字时,我的问题出现了,它仍然会向我的计数器添加一个数字,并将该数字添加到总数中,因此平均值会被丢弃。我绞尽脑汁,几乎尝试了一切方法来解决这个问题。代码有点草率,因为我还没有清理它,我只是想先整理一下移动部分。

public class StudentSentinel {

  public static void main(String[] args) {
    double score;
    double total = 0.0;
    double average;
    int scoreCount = 0;

    // create the Scanner object. Name it stdin
    Scanner stdin = new Scanner(System.in);

    // title at the top of the output
    System.out.println(" student score report");;

    //   read the first score
    System.out.printf("Enter a score  (1-100, -1 to quit)" +
      ": ", scoreCount);

    score = stdin.nextDouble();
    scoreCount++;

    while (score != -1.0) {

      total += score;
      System.out.printf("Enter a score  (1-100, -1 to quit)" +
        ": ", scoreCount);
      scoreCount++;
      score = stdin.nextDouble();
      if (score < -1)
        System.out.println("Illegal score.  Try again");
      else if (score > 100) {
        System.out.println("Illegal score.  Try again");
      }
      // increment the loop counter
    }
    // end of for loop
    average = total / scoreCount;
    System.out.printf("\nThe average score for %d students is %8.2f\n",
      scoreCount, average);
  } // end of main    
} // end of class definition

最佳答案

首先检查分数是否合法,然后增加计数器并将其添加到您的总分中。您还可以分配 score 并通过单个操作检查其是否为 -1。并始终使用大括号(即使它们是可选的)。就像,

// read the first score
System.out.printf("Enter a score  (1-100, -1 to quit)" + ": ", scoreCount);
while ((score = stdin.nextDouble()) != -1.0) {
    if (score < -1 || score > 100) {
        System.out.println("Illegal score.  Try again");
    } else {
        scoreCount++;
        total += score;
    }
    System.out.printf("Enter a score  (1-100, -1 to quit)" + ": ", scoreCount);
}

关于java - 如何使无效数字不添加到我的最终计算和计数器总计中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52682876/

相关文章:

java - Java 套接字中的写入是否可能在没有同时读取抛出的情况下抛出?

java - Vista 上 System.loadlibrary() 的替代方案

java - ANTLR4 语法仅匹配解析器规则的第一部分

java - 了解使用二进制补码写入 bluej 的程序。

java - 语法错误,插入 "... VariableDeclaratorId"以完成 FormalParameterList

java - XINS 以外的 Java 的 eXtreme Design-by-Contract?

java - 如何在morphia和mongodb中通过外键(dbref)查找记录?

java - 如何从 4 个 Excel 工作表中用 Java 数据创建单个数据库表?

Java服务器一遍又一遍地接收相同的数据

java - 以编程方式添加 Spring 拦截器,无需应用程序描述符