繁体   English   中英

如何让我的输入验证工作,以便 -1 - 100 范围之外的任何内容都将显示错误消息?

[英]How can I get my input validation to work so anything outside range -1 - 100 will display the error message?

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);
            score = promptForInt(message, 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;
}

如何让我的输入验证工作,以便 -1 - 100 范围之外的任何内容都将显示错误消息? 我想使用“do-while”循环,并认为我做对了。 如果用户输入了超出定义范围的值,则应显示错误消息并再次提示输入分数。 我错过了什么?

  1. 进行验证的一个好地方是在方法promptForInt
  2. 由于没有使用从方法promptForInt返回的值,最好将其声明为void
  3. 不要在循环内实例化Scanner对象。

以下代码包含了所有这些注释:

import java.util.Scanner;

public class Main {
    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);
    }

    public static void promptForInt(String message, int minValue, int maxValue) {
        // Declaring variables for the loop & the sentinel variable
        int sum = 0;
        int numStudents = 0;
        int score = 0;
        boolean valid;
        Scanner keyboard = new Scanner(System.in);

        System.out.println(message);

        // Loop to continue getting score for students until -1 is entered to quit
        do {
            System.out.printf("Enter the score for student #%d" + "(or -1 to quit): ", numStudents);
            // Loop for getting input of score for the current student
            do {
                valid = true;
                score = Integer.parseInt(keyboard.nextLine());
                // 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);
                    valid = false;
                }
            } while (!valid);

            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 " + convertToLetter(avgScore));
    }

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

示例运行:

Welcome to Simple Gradebook!
Enter the score for student #0(or -1 to quit): -2
Invalid value. The acceptable range is between -1 and 100
Please try again
-4
Invalid value. The acceptable range is between -1 and 100
Please try again
45
Enter the score for student #1(or -1 to quit): 50
Enter the score for student #2(or -1 to quit): -1
The average score is: 47.5 which equates to a F

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM