简体   繁体   中英

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? I want to use the "do-while" loop and thought I was doing it all correctly. 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 .
  2. Since there is no use of the value returned from method, promptForInt , it's better to declare it as void .
  3. Do not instantiate the Scanner object inside the loop.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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