简体   繁体   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;
}

How can I get my input validation to work so anything outside range -1 - 100 will display the error message?如何让我的输入验证工作,以便 -1 - 100 范围之外的任何内容都将显示错误消息? I want to use the "do-while" loop and thought I was doing it all correctly.我想使用“do-while”循环,并认为我做对了。 If a user enters a value outside the defined range, it should display the error message and prompt again for the score.如果用户输入了超出定义范围的值,则应显示错误消息并再次提示输入分数。 What am I missing?我错过了什么?

  1. A good place to do the validation is inside the method, promptForInt .进行验证的一个好地方是在方法promptForInt
  2. Since there is no use of the value returned from method, promptForInt , it's better to declare it as void .由于没有使用从方法promptForInt返回的值,最好将其声明为void
  3. Do not instantiate the Scanner object inside the loop.不要在循环内实例化Scanner对象。

The following code has incorporated all these comments:以下代码包含了所有这些注释:

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

A sample run:示例运行:

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.

相关问题 如何检查用户是否未输入任何内容,以便显示错误消息 - How do I check if a user inputs nothing so I can display an error message 我如何从推送通知服务中获取消息并显示到消息活动中 - how can i get the message from my push notification service and display to my message activity Integers.parseint(在扫描仪输入上),我也想进行限制,因此用户只能输入0到100范围内的数字 - Integers.parseint( on scanner input ), also i want to make limits so user can only input number in range from 0 to 100 我希望我的程序在用户输入除整数以外的任何内容并将其循环回时显示错误消息 - I want my program to display an error message when the user inputs anything other than an integer and loop it back 为什么我可以为我的操作输入任何东西? - Why can i input anything for my operation? 如何在字符串缓冲区输入循环之外获取http请求的输入流结果 - How can I get my inputstream result of a http request outside the string buffer input loop 我如何在 Java 中显示错误消息 - How can i display an error message in Java 如果数字超出范围,如果语句提示用户出现错误消息,我如何获取Java - how can i get java if statment promopt a user with error message when a number out of the range 如何在JOptionPane消息中显示JTextfield输入? - How can I display JTextfield input, in an JOptionPane message? 在java中,我如何检查用于输入成绩的数组的输入验证(不能为负数,不能超过100) - In java, How would I check input validation for an array used to input grades (can't be negative, can't be over 100)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM