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

huangapple go评论62阅读模式
英文:

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

Please note that I have only provided the translation for the code, as requested. If you have any specific questions or need further assistance with the code, feel free to ask.

英文:
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);
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 &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;
}

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

得分: 0

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;
    }
}
英文:
  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 = &quot;Welcome to Simple Gradebook!&quot;;
promptForInt(message, minValue, maxValue);
}
public static void 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;
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(&quot;Enter the score for student #%d&quot; + &quot;(or -1 to quit): &quot;, numStudents);
// Loop for getting input of score for the current student
do {
valid = true;
score = Integer.parseInt(keyboard.nextLine());
// 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);
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(&quot;The average score is: &quot; + avgScore + &quot; which equates to a &quot; + convertToLetter(avgScore));
}
public static char convertToLetter(double avg) {
char gradeLetter;
// Identifying the ranges for the grade letter
if (avg &gt;= 90) {
gradeLetter = &#39;A&#39;;
} else if (avg &gt;= 80) {
gradeLetter = &#39;B&#39;;
} else if (avg &gt;= 70) {
gradeLetter = &#39;C&#39;;
} else if (avg &gt;= 60) {
gradeLetter = &#39;D&#39;;
} else {
gradeLetter = &#39;F&#39;;
}
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

huangapple
  • 本文由 发表于 2020年10月4日 06:12:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/64189489.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定