简体   繁体   English

我怎样才能让我的打印语句在打印平均分数和相关字母等级的地方工作?

[英]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)
    {

        // Defining the constants for min and max range
        final int minValue = -1;
        final int maxValue = 100;
        String message = "Welcome to Simple Gradebook!";

        promptForInt(message, minValue, maxValue);

        // Declaring variables for the loop & the sentinel variable
        int score = 0;
        boolean doneYet = false;

        do
        {
            // Input Validation
            if (score < minValue || score > maxValue)
            {
                System.err.printf("Invalid value. The acceptable range is"
                        + " between %d and %d\n"
                        + "Please try again\n", minValue, maxValue);
            }
            else
            {
                doneYet = true;
            }
        } while (doneYet == false);

    }

    public static int promptForInt(String message, int minValue, int maxValue)
    {
        // Declaring variables for the loop & the sentinel variable
        int sum = 0;
        int numStudents = 0;
        int score = 0;

        System.out.println(message);

        //Creating the sentinel loop
        do
        {
            System.out.printf("Enter the score for student #%d"
                    + "(or -1 to quit): ", 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("The average score is: " + avgScore
                + " which equates to a " + avgScore);
        return 0;

    }

    public static char convertToLetter(double avg)
    {
        char avgScore = 0;
        // Identifying the ranges for the grade letter
        if (avgScore >= 90)
        {
            System.out.println("A");
        }
        else if (avg >= 80)
        {
            System.out.println("B");
        }
        else if (avg >= 70)
        {
            System.out.println("C");
        }
        else if (avg >= 60)
        {
            System.out.println("D");
        }
        else
        {
            System.out.println("F");
        }
        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”像这样……“平均分是90.5,相当于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 或大于 100,则应给出错误消息并再次开始循环。

You're not doing anything with the result of convertToLetter(avgScore) .您没有对convertToLetter(avgScore)的结果做任何事情。

Assign the result to a variable:将结果分配给变量:

char grade = convertToLetter(avgScore);

Then refer to that variable when printing:然后在打印时引用该变量:

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

—-- ----

You have a similar problem when calling promptForInt(message, minValue, maxValue) ;您在调用promptForInt(message, minValue, maxValue)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.如果score不在范围内,则do while循环将无限循环,因为score的值不会在循环内的任何地方更改。

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.为在convertToLetter方法中声明的avgScore变量赋值对在 main 方法中声明的同名变量没有任何影响 - 它们是不同的变量,其范围仅限于声明它们的方法。

  1. You are not assigning and returning the grade letter from the function, convertToLetter correctly.您没有从函数convertToLetter正确分配和返回成绩字母。
  2. You are not printing the return value of the function, convertToLetter .您没有打印函数convertToLetter的返回值。

Write the function as shown below:编写如下所示的函数:

public static char convertToLetter(double avg) {
    char gradeLetter;
    // Identifying the ranges for the grade letter
    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;
}

and then change the print statement as System.out.println("The average score is: " + avgScore + " which equates to a " + convertToLetter(avgScore));然后将打印语句更改为System.out.println("The average score is: " + avgScore + " which equates to a " + convertToLetter(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 = "Welcome to Simple Gradebook!";
        System.out.println(message);

        // Declaring variables for the loop & 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("No data received.");
        }
        else {
            double avgScore = (double) sum / numStudents;
            char letter = convertToLetter(avgScore);
            System.out.printf("The average score is: %.3f which equates to a %c%n",
                              avgScore,
                              letter);
        }
    }

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

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

    public static char convertToLetter(double avg) {
        char avgScore = 0;
        // Identifying the ranges for the grade letter
        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;
    }
}

Method promptForInt() should accept a single score from the user and return it.方法promptForInt()应该接受来自用户的单个分数并返回它。 It should return only a valid score.它应该只返回一个有效的分数。

Method main() contains the loop for gathering up all the scores.方法main()包含用于收集所有分数的循环。

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.方法convertToLetter()总是将零值avgScore ,本质上使avgScore成为空字符。

Here is a sample run of the program.这是该程序的示例运行。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用switch()语句将数字转换为字母等级? - How can I use a switch() statement to convert from a numeric to a letter grade? 我如何使平均成绩参考我在If-Else声明中创建的成绩 - How do i make average grade refer to grade which i created in If-Else Statement 如何获得我的学生成绩计算器程序中类似成绩字母的总数 - how can i get the total number of similar grade letters in my student grade calculator program 如何创建一个窗口来运行我的字母分级程序? - How do I create a window to run my letter grade program in? Java - 如何在我的程序中显示我的每个成绩的字母成绩,而不仅仅是我的最后一个成绩? - Java - How can I display a letter grade for each of my grades in my program rather than just my last one? 我怎样才能让我的 if else 语句起作用? - How can i get my if else statement to work? 我需要在课堂上显示学生的数字标记以及他们的字母成绩。 我的代码不输出字母。 我怎样才能解决这个问题? - I need to display a student's numerical mark in a class as well as their letter grade. My code does not output the letter. How can I fix this? 必须使用这种布局,我如何获得要打印的成绩? - having to use this layout, how do I get the grade to print? 使用Javabean评分书; 我如何获得整体平均水平? - Score book using javabean; how do I get overall average? 如何打印此文件中行的平均值? - How can I print the average of the lines in this file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM