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

go评论56阅读模式

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;

// 将方法传递给此方法以将分数转换为字母等级
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

``````char grade = convertToLetter(avgScore);
``````

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

—--

``````score = promptForInt(message, minValue, maxValue);
``````

``````score = promptForInt(message, minValue, maxValue);
``````

—--

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

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

``````public static char convertToLetter(double avg) {
// 识别等级字母的范围
if (avg >= 90) {
} else if (avg >= 80) {
} else if (avg >= 70) {
} else if (avg >= 60) {
} else {
}
}
``````

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) {
// Identifying the ranges for the grade letter
if (avg &gt;= 90) {
} else if (avg &gt;= 80) {
} else if (avg &gt;= 70) {
} else if (avg &gt;= 60) {
} else {
}
}
``````

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

``````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;
}
}
``````

``````欢迎来到简单的成绩记录系统！

``````

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) {
}
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
``````

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

go 78

go 54

go 75

go 66