检测特定用户输入,而无需在 while 循环中首先处理它。

huangapple go评论66阅读模式
英文:

Detecting a particular user input without first processing it in a while loop

问题

import java.util.Scanner;

public class Lab4_EnteringGrades
{
    public static void main(String a[])
    {
        Scanner kb = new Scanner(System.in);

        double average = 0;
        double gradesSum = 0;
        int grade = 0;
        int numTests = 0;
        int maxValue = 0;
        int minValue = 0;

        while (grade != -1)
        {
            gradesSum += grade;
            numTests += 1;
            average = gradesSum / numTests;

            System.out.print("Enter a grade: ");
            grade = kb.nextInt();

            while ((grade < -1) || (grade > 100))
            {
                System.out.println("Invalid grade.");
                System.out.print("Enter a grade: ");
                grade = kb.nextInt();
            }

            if (grade > maxValue)
                maxValue = grade;

            if (minValue == 0 || grade < minValue)
                minValue = grade;
        }

        System.out.printf("\nTotal number of tests: %d", numTests);
        System.out.printf("\nThe average is %.1f", average);
        System.out.printf("\nThe max value is %d", maxValue);
        System.out.printf("\nThe min value is %d", minValue);
    }
}
英文:

I have this program where the user inputs x amount of grades, then the program divides the sum of the grades by the number of inputs taken. It should also find the highest and lowest grades entered. When the user is finished, he/she types in -1 to end the program. However, I am having some issues with it.

  1. The program adds -1 to the average which skews all my results.
  2. I can't figure out how to calculate the minimum value in the list. It always counts -1 as the minimum value.

Here is the code below:

import java.util.Scanner;
public class Lab4_EnteringGrades
{
public static void main (String a[]) 
{    
Scanner kb = new Scanner(System.in); 
double average = 0;
double gradesSum = 0;
int grade = 0; 
int numTests = 0;
int maxValue = 0;
int minValue = 0;
while (grade != -1)
{
gradesSum += grade; 
numTests += 1; 
average = gradesSum / numTests;
System.out.print(&quot;Enter a grade: &quot;);
grade = kb.nextInt();
while ((grade &lt; -1) || (grade &gt; 100))
{
System.out.println(&quot;Invalid grade.&quot;);
System.out.print(&quot;Enter a grade: &quot;);
grade = kb.nextInt();
}     
if (grade &gt; maxValue)
maxValue = grade;
if (grade &lt; maxValue)
minValue = grade;
}
System.out.printf(&quot;\nTotal number of tests: %d&quot;, numTests);
System.out.printf(&quot;\nThe average is %.1f&quot;, average);
System.out.printf(&quot;\nThe max value is %d&quot;, maxValue);
System.out.printf(&quot;\nThe min value is %d&quot;, minValue);
}
}

答案1

得分: 4

我做了一些更改 -

  1. 在您的原始代码中,对minValuemaxValue的初始化,minValue为-1,且grade不能小于-1,因此您总是看到minValue为-1。一般来说,如果您想要最小和最大值,最好像我在这里做的那样进行初始化。

  2. 在用户输入grade之后,将计算gradeaverage的逻辑移动到之前,以避免破坏average的计算。

  3. 您的原始代码是:

> if (grade < maxValue)

我将其更改为if (grade &lt; minValue)。我认为这是一个打字错误。

import java.util.Scanner;

public class Lab4_EnteringGrades {
    public static void main (String a[])
    {
        Scanner kb = new Scanner(System.in);

        double average = 0;
        double gradesSum = 0;
        int grade = 0;
        int numTests = 0;
        int maxValue = Integer.MIN_VALUE;
        int minValue = Integer.MAX_VALUE;


        while (true)
        {

            System.out.print("Enter a grade: ");
            grade = kb.nextInt();

            while ((grade &lt; -1) || (grade &gt; 100))
            {
                System.out.println("Invalid grade.");
                System.out.print("Enter a grade: ");
                grade = kb.nextInt();
            }
            if (grade == -1) {
                break;
            }

            gradesSum += grade;
            numTests += 1;
            average = gradesSum / numTests;


            if (grade &gt; maxValue)
                maxValue = grade;

            if (grade &lt; minValue)
                minValue = grade;
        }

        System.out.printf("\nTotal number of tests: %d", numTests);
        System.out.printf("\nThe average is %.1f", average);
        System.out.printf("\nThe max value is %d", maxValue);
        System.out.printf("\nThe min value is %d", minValue);
    }
}
英文:

I made few changes -

  1. Initialization of minValue and maxValue , in your original code, minValue was -1 and grade could not be less than -1, hence you always saw minValue as -1.
    In general, if you want min and max vales, it is better to initialize like I did here.

  2. Moved the logic of calculating grade, average AFTER user has entered the grade in order not to mess up the average.

  3. Your original code was:

> if (grade < maxValue)

I changed this to be if (grade &lt; minValue). I believe it was a typo.

import java.util.Scanner;
public class Lab4_EnteringGrades {
public static void main (String a[])
{
Scanner kb = new Scanner(System.in);
double average = 0;
double gradesSum = 0;
int grade = 0;
int numTests = 0;
int maxValue = Integer.MIN_VALUE;
int minValue = Integer.MAX_VALUE;
while (true)
{
System.out.print(&quot;Enter a grade: &quot;);
grade = kb.nextInt();
while ((grade &lt; -1) || (grade &gt; 100))
{
System.out.println(&quot;Invalid grade.&quot;);
System.out.print(&quot;Enter a grade: &quot;);
grade = kb.nextInt();
}
if (grade == -1) {
break;
}
gradesSum += grade;
numTests += 1;
average = gradesSum / numTests;
if (grade &gt; maxValue)
maxValue = grade;
if (grade &lt; minValue)
minValue = grade;
}
System.out.printf(&quot;\nTotal number of tests: %d&quot;, numTests);
System.out.printf(&quot;\nThe average is %.1f&quot;, average);
System.out.printf(&quot;\nThe max value is %d&quot;, maxValue);
System.out.printf(&quot;\nThe min value is %d&quot;, minValue);
} }

答案2

得分: 3

问题在于:

  1. 在读取第一个成绩之前,您执行了 gradesSum += grade;,而此时 grade 仍为 0
  2. 在用户输入 grade=-1; 之后,您执行了 if (grade &lt; maxValue),因此始终会发现 -1 较小。
  3. 您在检查最大值和最小值时都将成绩与 maxValue 进行比较。
  4. 由于您初始化了 minValue=0,除了 -1 之外,您永远不会找到更小的值,因此您应该将其初始化为较大的值。

您可以将处理成绩的所有代码移到读取成绩之后,并且如果用户输入 -1,则使用 break 结束:

import java.util.Scanner;

public class Lab4_EnteringGrades
{
  public static void main (String a[])
  {
    Scanner kb = new Scanner(System.in);

    double average = 0;
    double gradesSum = 0;
    int grade = 0;
    int numTests = 0;
    int maxValue = 0;
    int minValue = 101;

    while (true)
    {
      System.out.print("Enter a grade: ");
      grade = kb.nextInt();

      while ((grade < -1) || (grade > 100))
      {
        System.out.println("Invalid grade.");
        System.out.print("Enter a grade: ");
        grade = kb.nextInt();
      }

      // 如果用户输入 -1,则退出循环
      if (grade == -1) break;

      gradesSum += grade;
      numTests += 1;
      average = gradesSum / numTests;

      if (grade > maxValue)
        maxValue = grade;

      if (grade < minValue)
        minValue = grade;
    }

    System.out.printf("\nTotal number of tests: %d", numTests);
    System.out.printf("\nThe average is %.1f", average);
    System.out.printf("\nThe max value is %d", maxValue);
    System.out.printf("\nThe min value is %d", minValue);
  }
}

然而,while(true) { if(..) break; } 的写法稍显繁琐。您可以通过创建一个单独的函数来改进代码以读取输入:

import java.util.Scanner;

public class Lab4_EnteringGrades
{
  public static int readGrade(Scanner kb) {
    System.out.print("Enter a grade: ");
    int grade = kb.nextInt();

    while ((grade < -1) || (grade > 100))
    {
      System.out.println("Invalid grade.");
      System.out.print("Enter a grade: ");
      grade = kb.nextInt();
    }
    return grade;
  }

  public static void main (String a[])
  {
    Scanner kb = new Scanner(System.in);

    double average;
    double gradesSum = 0;
    int grade;
    int numTests = 0;
    int maxValue = Integer.MIN_VALUE;
    int minValue = Integer.MAX_VALUE;

    // 使用常见的方法读取成绩,直到为 -1
    while ((grade = readGrade(kb)) != -1) {
      gradesSum += grade;
      numTests += 1;

      if (grade > maxValue)
        maxValue = grade;

      if (grade < minValue)
        minValue = grade;
    }
    // 考虑处理 numTests == 0 的情况
    average = gradesSum / numTests;

    System.out.printf("\nTotal number of tests: %d", numTests);
    System.out.printf("\nThe average is %.1f", average);
    System.out.printf("\nThe max value is %d", maxValue);
    System.out.printf("\nThe min value is %d", minValue);
  }
}
英文:

The problems are that

  1. You do gradesSum += grade; before reading the first grade, when grade is still 0.
  2. You do if (grade &lt; maxValue) after the user has entered grade=-1;, thus always find that -1 is smaller.
  3. You compare the grade to maxValue both for checking max and min
  4. Since you initialize minValue=0, you won't ever find a smaller value (except -1), so you should initialize it to something larger

You can move all the code that processes the grade until after you've read it, and then break if the user enters -1:

import java.util.Scanner;

public class Lab4_EnteringGrades
{
public static void main (String a[])
  {
  Scanner kb = new Scanner(System.in);

  double average = 0;
  double gradesSum = 0;
  int grade = 0;
  int numTests = 0;
  int maxValue = 0;
  int minValue = 101;

  while (true)
     {
     System.out.print(&quot;Enter a grade: &quot;);
     grade = kb.nextInt();

     while ((grade &lt; -1) || (grade &gt; 100))
        {
        System.out.println(&quot;Invalid grade.&quot;);
        System.out.print(&quot;Enter a grade: &quot;);
        grade = kb.nextInt();
        }

     // Stop if the user entered -1
     if (grade == -1) break;

     gradesSum += grade;
     numTests += 1;
     average = gradesSum / numTests;

     if (grade &gt; maxValue)
        maxValue = grade;

     if (grade &lt; minValue)
        minValue = grade;
     }

  System.out.printf(&quot;\nTotal number of tests: %d&quot;, numTests);
  System.out.printf(&quot;\nThe average is %.1f&quot;, average);
  System.out.printf(&quot;\nThe max value is %d&quot;, maxValue);
  System.out.printf(&quot;\nThe min value is %d&quot;, minValue);
  }
}

The while(true) { if(..) break; } is slightly awkward though. You can improve the code further by creating a separate function for reading input:

import java.util.Scanner;

public class Lab4_EnteringGrades
{
  public static int readGrade(Scanner kb) {
    System.out.print(&quot;Enter a grade: &quot;);
    int grade = kb.nextInt();

    while ((grade &lt; -1) || (grade &gt; 100))
    {
      System.out.println(&quot;Invalid grade.&quot;);
      System.out.print(&quot;Enter a grade: &quot;);
      grade = kb.nextInt();
    }
    return grade;
  }

  public static void main (String a[])
  {
    Scanner kb = new Scanner(System.in);

    double average;
    double gradesSum = 0;
    int grade;
    int numTests = 0;
    int maxValue = Integer.MIN_VALUE;
    int minValue = Integer.MAX_VALUE;

    // Common idiom for reading a grade until it&#39;s -1
    while ((grade = readGrade(kb)) != -1) {
      gradesSum += grade;
      numTests += 1;

      if (grade &gt; maxValue)
        maxValue = grade;

      if (grade &lt; minValue)
        minValue = grade;
    }
    // Consider handling the case of numTests == 0
    average = gradesSum / numTests;

    System.out.printf(&quot;\nTotal number of tests: %d&quot;, numTests);
    System.out.printf(&quot;\nThe average is %.1f&quot;, average);
    System.out.printf(&quot;\nThe max value is %d&quot;, maxValue);
    System.out.printf(&quot;\nThe min value is %d&quot;, minValue);
  }
}

huangapple
  • 本文由 发表于 2020年9月30日 08:17:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/64129282.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定