如何使我的打印语句起作用,以便打印平均分和相应的等级字母?

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

How can I get my print statement to work to where it prints the average score and the correlating letter grade?

问题

public static void main(String[] args)
{
    // 定义最小和最大范围的常量
    final int minValue = -1;
    final int maxValue = 100;
    String message = "欢迎来到简易成绩单!";

    promptForInt(message, minValue, maxValue);

    // 声明循环和哨兵变量
    int score = 0;
    boolean doneYet = false;

    do
    {
        // 输入验证
        if (score < minValue || score > maxValue)
        {
            System.err.printf("无效的值。可接受的范围为%d到%d之间\n请重试\n", minValue, maxValue);
        }
        else
        {
            doneYet = true;
        }
    } while (doneYet == false);

}

public static int promptForInt(String message, int minValue, int maxValue)
{
    // 声明循环和哨兵变量
    int sum = 0;
    int numStudents = 0;
    int score = 0;

    System.out.println(message);

    // 创建哨兵循环
    do
    {
        System.out.printf("输入第%d个学生的分数(输入-1退出): ", numStudents);
        Scanner keyboard = new Scanner(System.in);
        score = Integer.parseInt(keyboard.nextLine());

        if (score != -1)
        {
            sum += score;
            numStudents += 1;
        }

    } while (score != -1);
    double avgScore = (double) sum / numStudents;

    // 将方法传递给此方法以将分数转换为字母等级
    char letterGrade = convertToLetter(avgScore);
    System.out.println("平均分是: " + avgScore
            + " 对应的等级是: " + letterGrade);
    return 0;

}

public static char convertToLetter(double avg)
{
    char avgScore;
    // 根据分数范围确定等级
    if (avg >= 90)
    {
        avgScore = 'A';
        System.out.println("A");
    }
    else if (avg >= 80)
    {
        avgScore = 'B';
        System.out.println("B");
    }
    else if (avg >= 70)
    {
        avgScore = 'C';
        System.out.println("C");
    }
    else if (avg >= 60)
    {
        avgScore = 'D';
        System.out.println("D");
    }
    else
    {
        avgScore = 'F';
        System.out.println("F");
    }
    return avgScore;

}
英文:
 public static void main(String[] args)
{
// Defining the constants for min and max range
final int minValue = -1;
final int maxValue = 100;
String message = &quot;Welcome to Simple Gradebook!&quot;;
promptForInt(message, minValue, maxValue);
// Declaring variables for the loop &amp; the sentinel variable
int score = 0;
boolean doneYet = false;
do
{
// Input Validation
if (score &lt; minValue || score &gt; maxValue)
{
System.err.printf(&quot;Invalid value. The acceptable range is&quot;
+ &quot; between %d and %d\n&quot;
+ &quot;Please try again\n&quot;, minValue, maxValue);
}
else
{
doneYet = true;
}
} while (doneYet == false);
}
public static int promptForInt(String message, int minValue, int maxValue)
{
// Declaring variables for the loop &amp; the sentinel variable
int sum = 0;
int numStudents = 0;
int score = 0;
System.out.println(message);
//Creating the sentinel loop
do
{
System.out.printf(&quot;Enter the score for student #%d&quot;
+ &quot;(or -1 to quit): &quot;, numStudents);
Scanner keyboard = new Scanner(System.in);
score = Integer.parseInt(keyboard.nextLine());
if (score != -1)
{
sum += score;
numStudents += 1;
}
} while (score != -1);
double avgScore = (double) sum / numStudents;
//Passing method to this method to convert grade to letter
convertToLetter(avgScore);
System.out.println(&quot;The average score is: &quot; + avgScore
+ &quot; which equates to a &quot; + avgScore);
return 0;
}
public static char convertToLetter(double avg)
{
char avgScore = 0;
// Identifying the ranges for the grade letter
if (avgScore &gt;= 90)
{
System.out.println(&quot;A&quot;);
}
else if (avg &gt;= 80)
{
System.out.println(&quot;B&quot;);
}
else if (avg &gt;= 70)
{
System.out.println(&quot;C&quot;);
}
else if (avg &gt;= 60)
{
System.out.println(&quot;D&quot;);
}
else
{
System.out.println(&quot;F&quot;);
}
return avgScore;
}
}

How can I get my print statement to work to where it prints the average score and the correlating letter grade? Like this... “The average score is 90.5, which equates to an A”

My input validation is not working like it should for some reason. If a number lower that -1 or higher than 100 is entered, it should give the error message and begin the loop again.

答案1

得分: 0

你没有对 convertToLetter(avgScore) 的结果进行任何操作。

将结果赋值给一个变量:

char grade = convertToLetter(avgScore);

然后在打印时引用该变量:

System.out.println("The average score is: " + avgScore
  + " which equates to a " + grade);

—--

在调用 promptForInt(message, minValue, maxValue) 时也存在类似的问题;你需要将结果赋值给一个变量:

score = promptForInt(message, minValue, maxValue);

另一个主要的错误是你的输入检查代码。如果 score 不在范围内,你的 do while 循环会无限循环,因为 score 的值在循环内部任何地方都没有改变。

在打印错误消息后添加这行代码:

score = promptForInt(message, minValue, maxValue);

—--

总的来说,你必须意识到变量具有作用域。你在 convertToLetter 方法中声明的 avgScore 变量赋值对于在主方法中声明的同名变量没有任何影响 - 它们是不同的变量,其作用域限于它们被声明的方法内部。

英文:

You’re not doing anything with the result of convertToLetter(avgScore).

Assign the result to a variable:

char grade = convertToLetter(avgScore);

Then refer to that variable when printing:

System.out.println(&quot;The average score is: &quot; + avgScore
+ &quot; which equates to a &quot; + grade);

—--

You have a similar problem when calling promptForInt(message, minValue, maxValue); you need to assign the result to a variable:

score = promptForInt(message, minValue, maxValue);

Another major bug you have is your input checking code. If score is not in range, your do while loop will loop infinitely because the value of score is not changed anywhere inside the loop.

Add this line after printing the error message:

score = promptForInt(message, minValue, maxValue);

—--

In general, you must realise that variables have scope. You assigning a value to the avgScore variable declared inside the convertToLetter method has no effect whatsoever on the variable of the same name declared in your main method - they are different variables, whose scope is limited to the method in which they are declared.

答案2

得分: 0

  1. 你没有正确地在函数 convertToLetter 中进行赋值和返回等级字母。
  2. 你没有打印函数 convertToLetter 的返回值。

按照以下方式编写函数:

public static char convertToLetter(double avg) {
    char gradeLetter;
    // 识别等级字母的范围
    if (avg >= 90) {
        gradeLetter = 'A';
    } else if (avg >= 80) {
        gradeLetter = 'B';
    } else if (avg >= 70) {
        gradeLetter = 'C';
    } else if (avg >= 60) {
        gradeLetter = 'D';
    } else {
        gradeLetter = 'F';
    }
    return gradeLetter;
}

然后将打印语句更改为 System.out.println("The average score is: " + avgScore + " which equates to a " + convertToLetter(avgScore));

英文:
  1. You are not assigning and returning the grade letter from the function, convertToLetter correctly.
  2. You are not printing the return value of the function, convertToLetter.

Write the function as shown below:

public static char convertToLetter(double avg) {
char gradeLetter;
// Identifying the ranges for the grade letter
if (avg &gt;= 90) {
gradeLetter = &#39;A&#39;;
} else if (avg &gt;= 80) {
gradeLetter = &#39;B&#39;;
} else if (avg &gt;= 70) {
gradeLetter = &#39;C&#39;;
} else if (avg &gt;= 60) {
gradeLetter = &#39;D&#39;;
} else {
gradeLetter = &#39;F&#39;;
}
return gradeLetter;
}

and then change the print statement as System.out.println(&quot;The average score is: &quot; + avgScore + &quot; which equates to a &quot; + convertToLetter(avgScore));

答案3

得分: 0

这段代码可以正常运行。解释在后面。

import java.util.Scanner;

public class Calculat {
    public static void main(String[] args) {

        Scanner keyboard = new Scanner(System.in);

        // 定义最小和最大范围的常量
        final int minValue = -1;
        final int maxValue = 100;

        String message = "欢迎来到简单的成绩记录系统!";
        System.out.println(message);

        // 为循环和哨兵变量声明变量
        int score = 0;
        int sum = 0;
        int numStudents = 0;

        while (true) {
            score = promptForInt(keyboard, (numStudents + 1), minValue, maxValue);
            if (score == -1) {
                break;
            }
            sum += score;
            numStudents++;
        }
        if (numStudents == 0) {
            System.out.println("未接收到数据。");
        }
        else {
            double avgScore = (double) sum / numStudents;
            char letter = convertToLetter(avgScore);
            System.out.printf("平均分为:%.3f,对应等级:%c%n",
                              avgScore,
                              letter);
        }
    }

    public static int promptForInt(Scanner keyboard, int numStudent, int minValue, int maxValue) {
        // 为循环和哨兵变量声明变量
        int score = 0;
        boolean isValidScore = false;

        // 创建哨兵循环
        do {
            System.out.printf("输入第 %d 位学生的分数(或输入 -1 退出):", numStudent);
            String line = keyboard.nextLine();
            try {
                score = Integer.parseInt(line);
                if (score < minValue || score > maxValue) {
                    System.out.printf("无效值。接受范围在 %d 和 %d 之间%n",
                                      minValue,
                                      maxValue);
                }
                else {
                    isValidScore = true;
                }
            }
            catch (NumberFormatException xNumberFormat) {
                System.out.printf("不是数字:%s%n", line);
            }
        } while (!isValidScore);
        return score;
    }

    public static char convertToLetter(double avg) {
        char avgScore = 0;
        // 确定等级字母的范围
        if (avg >= 90) {
            avgScore = 'A';
        }
        else if (avg >= 80) {
            avgScore = 'B';
        }
        else if (avg >= 70) {
            avgScore = 'C';
        }
        else if (avg >= 60) {
            avgScore = 'D';
        }
        else {
            avgScore = 'F';
        }
        return avgScore;
    }
}

方法 promptForInt() 应该从用户接收一个分数并返回它。它应该只返回有效的分数。

方法 main() 包含了收集所有分数的循环。

你需要检查至少输入了一个分数,否则无法计算平均分。

方法 convertToLetter() 一直将值零分配给 avgScore,实际上将 avgScore 设置为了空字符。

以下是程序的一个示例运行。

欢迎来到简单的成绩记录系统!
输入第 1 位学生的分数(或输入 -1 退出):66
输入第 2 位学生的分数(或输入 -1 退出):66
输入第 3 位学生的分数(或输入 -1 退出):68
输入第 4 位学生的分数(或输入 -1 退出):-1
平均分为:66.667,对应等级:D
英文:

This code works. Explanations after.

import java.util.Scanner;

public class Calculat {
    public static void main(String[] args) {

        Scanner keyboard = new Scanner(System.in);

        // Defining the constants for min and max range
        final int minValue = -1;
        final int maxValue = 100;

        String message = &quot;Welcome to Simple Gradebook!&quot;;
        System.out.println(message);

        // Declaring variables for the loop &amp; the sentinel variable
        int score = 0;
        int sum = 0;
        int numStudents = 0;

        while (true) {
            score = promptForInt(keyboard, (numStudents + 1), minValue, maxValue);
            if (score == -1) {
                break;
            }
            sum += score;
            numStudents++;
        }
        if (numStudents == 0) {
            System.out.println(&quot;No data received.&quot;);
        }
        else {
            double avgScore = (double) sum / numStudents;
            char letter = convertToLetter(avgScore);
            System.out.printf(&quot;The average score is: %.3f which equates to a %c%n&quot;,
                              avgScore,
                              letter);
        }
    }

    public static int promptForInt(Scanner keyboard, int numStudent, int minValue, int maxValue) {
        // Declaring variables for the loop &amp; the sentinel variable
        int score = 0;
        boolean isValidScore = false;

        // Creating the sentinel loop
        do {
            System.out.printf(&quot;Enter the score for student #%d (or -1 to quit): &quot;, numStudent);
            String line = keyboard.nextLine();
            try {
                score = Integer.parseInt(line);
                if (score &lt; minValue || score &gt; maxValue) {
                    System.out.printf(&quot;Invalid value. Acceptable range is between %d and %d%n&quot;,
                                      minValue,
                                      maxValue);
                }
                else {
                    isValidScore = true;
                }
            }
            catch (NumberFormatException xNumberFormat) {
                System.out.printf(&quot;Not a number: %s%n&quot;, line);
            }
        } while (!isValidScore);
        return score;
    }

    public static char convertToLetter(double avg) {
        char avgScore = 0;
        // Identifying the ranges for the grade letter
        if (avg &gt;= 90) {
            avgScore = &#39;A&#39;;
        }
        else if (avg &gt;= 80) {
            avgScore = &#39;B&#39;;
        }
        else if (avg &gt;= 70) {
            avgScore = &#39;C&#39;;
        }
        else if (avg &gt;= 60) {
            avgScore = &#39;D&#39;;
        }
        else {
            avgScore = &#39;F&#39;;
        }
        return avgScore;
    }
}

Method promptForInt() should accept a single score from the user and return it. It should return only a valid score.

Method main() contains the loop for gathering up all the scores.

You need to check that at least one score was entered, otherwise you can't calculate the average.

Method convertToLetter() was always assigning the value zero to avgScore, essentially making avgScore the null character.

Here is a sample run of the program.

<!-- language: lang-none -->

Welcome to Simple Gradebook!
Enter the score for student #1 (or -1 to quit): 66
Enter the score for student #2 (or -1 to quit): 66
Enter the score for student #3 (or -1 to quit): 68
Enter the score for student #4 (or -1 to quit): -1
The average score is: 66.667 which equates to a D

huangapple
  • 本文由 发表于 2020年10月4日 03:49:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/64188367.html
匿名

发表评论

匿名网友

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

确定