java - 我正在尝试编写一个程序,允许用户输入一系列考试分数作为整数

标签 java

我正在尝试编写一个程序,允许用户以整数形式输入一系列考试分数。

我希望输出看起来像这样:

输入一个整数,或 -99 退出:80

输入一个整数,或 -99 退出:95

输入一个整数,或 -99 退出:65

输入一个整数,或-99退出:-99

最大:95 最小:65

第二次运行:

输入一个整数,或-99退出:-99

您没有输入任何数字。

我记下了第一部分,但当我输入 -99 时,我似乎无法找到如何获得“您没有输入任何数字”行。

这就是我到目前为止所拥有的。

import java.util.Scanner;    // Needed for the Scanner class

/**
   This program shows the largest and smallest exam scores. The user
   enters a series of exam scores, then -99 when finished.
   UPDATED to show even number of points using if-statement
*/

public class Grades
{
   public static void main(String[] args)
   {
      int score = 0;       // Exam score
      int min = 100;       // Hold smallest score
      int max = 0;         // Hold largest score

      // Create a Scanner object for keyboard input.
      Scanner keyboard = new Scanner(System.in);

      // Display general instructions.
      System.out.println("Enter an integer, or -99 to quit: ");
      System.out.println();

      // Get the first exam score.
      System.out.print("Enter an integer, or -99 to quit: ");
      score = keyboard.nextInt();

      // Input exam scores until -99 is entered.
      while (score != -99)
      {
         // Add points to totalPoints.
         if (score > max)
            max = score;
         if (score < min)
            min = score;
         // Get the next number of points.
         System.out.print("Enter an integer, or -99 to quit: ");
         score = keyboard.nextInt();
      }

      // Display the largest and smallest score.
      System.out.println("Largest: " + max);
      System.out.println("Smallest: " + min);
   }
}

最佳答案

引入一个变量来计算输入的数字并在 while 循环中增加怎么样?

或者作为替代方案,您可以在 while 循环之后检查数字是否发生变化:

if(min > max) {
    System.out.println("You did not enter any numbers.");
}
else {
    System.out.println("Largest: " + max);
    System.out.println("Smallest: " + min);
}

这是可行的,因为一开始您将 min 变量初始化为 100,将 max 变量初始化为 0如果没有输入数字,则 min > max 检查将得到 true

关于java - 我正在尝试编写一个程序,允许用户输入一系列考试分数作为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40084686/

相关文章:

java - 如何利用 Spring MVC 实现前端 Controller 但不使用 Controller

java - C服务器和Java客户端之间的UDP连接

java - 无法让 Servlet 以 UTF-8 格式处理请求内容

java - 使用 Apache FTPClient 通过代理连接到 FTP 服务器

java - 将数据添加到 JTable 部分代码,转换问题

java - 文本出现在启动屏幕后

java - 从 ant 更改 javac 路径

java - Linux从Java程序复制文件

java - 将超链接放入 <h :messages> tag

JavaFX8 禁用 ScrollPane 的滚动