[英]Java Creating a new method for user input error with do-while and for-loops
Alright, so I have this beauty of a code that I want to squish into a new method. 好了,所以我有一段代码的美丽之处,我想将其压缩为一种新方法。 So far I figured obviously the error reports will be inside the method.
到目前为止,我清楚地知道错误报告将在方法内部。 However, it's not as simple as that because while the grade count is an int the grade itself is a double and calculated under a for loop.
但是,这并不是那么简单,因为虽然成绩等级是一个整数,但成绩本身却是双精度,并且是在for循环下计算的。 Many ways I've tried do not even accept an input from the user.
我尝试过的许多方法甚至都不接受用户的输入。
I've tried looking around for a better example than a simple method format, but I have yet to find something similar to my problem. 我试图寻找一种比简单方法格式更好的示例,但是我还没有找到与我的问题类似的东西。 Is there a way to put both grade count and actual grade within the method for it to work?
有没有办法将成绩计数和实际成绩同时纳入工作方法? I've tried condensing code within a method before, but it was with a much simpler code than this one.
我以前尝试过在一种方法中压缩代码,但它的代码比此方法简单得多。
I get the idea of methods, but actually doing them is confusing. 我有方法的想法,但是实际上做这些方法是令人困惑的。 Help is super appreciated!!!!
帮助是非常感谢!!!
public static void main(String[] args) {
// create a console object from the Scanner class
Scanner input = new Scanner(System.in);
System.out.println("Welcome to average grade calculation service!");
String userChoice = null;
// Use a loop to repeat the average grade calculation
do {
// Use a loop to read the number and check the error
boolean isCorrectNumber = false;
// First, get the number of grades
int numberOfGrades = 0;
// Loop until the user enters a numeric number of grades
do {
// Prompt the user to enter the number of grades
System.out.print("\nEnter the number of grades: ");
// Check if the number of grades is not numeric
if (!input.hasNextInt()) {
// Display number input error
System.out.println("Error: The number of grades must be a number.");
input.nextLine(); // flush out the input
} else {
// Read the number of grades
numberOfGrades = input.nextInt();
// Check if the number of grade is negative
if (numberOfGrades < 0) {
// Display the non positive number error
System.out.println("Error: The number of grades must be positive.");
} else
isCorrectNumber = true; // End the data validation loop
}
} while (!isCorrectNumber); // continue until getting a correct data
//*** Second, get all these grades to compute the sum of the grades
// Declare variables for the sum of the grade and grade
double sumOfGrades = 0;
double aGrade = 0;
// Use a loop to read each grade
for (int i = 1; i <= numberOfGrades; i++) {
// Use a loop to read and validate each grade
isCorrectNumber = false;
do {
// Prompt the user to enter a grade
System.out.print("Enter grade " + i + ": ");
// Check if the grade is not numeric
if (!input.hasNextDouble()) {
// Display grade input error
System.out.println("Error: The grade must be a number.");
input.nextLine(); // flush out the input
} else {
// Read the grade
aGrade = input.nextDouble();
// Check if the grade is negative
if (aGrade < 0)
// Display negative grade input error
System.out.println("Error: The grade must be zero or positive.");
else
isCorrectNumber = true; // End the grade validation loop
}
} while (!isCorrectNumber); // continue until getting a correct grade
// Add the grade to the sum and continue the loop
sumOfGrades += aGrade;
}
input.nextLine();
// Compute the average grade only if the sum is greater than 0
double averageGrade = (sumOfGrades > 0)? sumOfGrades / numberOfGrades : 0;
// Display the average grade
System.out.printf("\nThe average grade is %4.2f\n", averageGrade);
// Prompt if the user want to continue the calculation
System.out.print("\nDo you want to continue (yes/no)? ");
userChoice = input.nextLine();
System.out.println("");
// Continue the loop if the user wants to continue the calculation
} while (userChoice.equalsIgnoreCase("yes"));
// Display an acknowledgement message
System.out.println("Thank you and have a nice day!");
input.close(); // release the console object
}
I'd break your method into few simpler methods. 我会将您的方法分解为一些更简单的方法。 Method should have a specific function.
方法应具有特定的功能。 It'll make it easier to define them and also to debug.
这将使定义它们和调试变得更加容易。 Also we can easily replace/modify the internal details of a method and it's users won't be affected.
同样,我们可以轻松地替换/修改方法的内部细节,并且不会影响用户。 In the following example I can modify how getGradeAvg method calculate the average and none of the other method needs to be changed.
在下面的示例中,我可以修改getGradeAvg方法如何计算平均值,而无需更改其他任何方法。
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to average grade calculation service!");
String userChoice = null;
do {
int numberOfGrades = getNumberOfGrades(input);
double averageGrade = getGradeAvg(numberOfGrades, input);
System.out.printf("\nThe average grade is %4.2f\n", averageGrade);
System.out.print("\nDo you want to continue (yes/no)? ");
userChoice = input.nextLine();
System.out.println("");
} while (userChoice.equalsIgnoreCase("yes"));
System.out.println("Thank you and have a nice day!");
input.close();
}
//this method is responsible of getting the number of grades
private static int getNumberOfGrades(Scanner input) {
int numberOfGrades = 0;
boolean isCorrectNumber;
do {
isCorrectNumber = false;
System.out.print("\nEnter the number of grades: ");
if (!input.hasNextInt()) {
System.out.println("Error: The number of grades must be a number.");
input.nextLine();
} else {
numberOfGrades = input.nextInt();
if (numberOfGrades < 0) {
System.out.println("Error: The number of grades must be positive.");
} else
isCorrectNumber = true;
}
} while (!isCorrectNumber);
return numberOfGrades;
}
/*
* this method takes the number of grades as a parameter
* then asks the user to input grade value of each grade
* then it calculate the average and returns the value
*/
private static double getGradeAvg(int numberOfGrades, Scanner input) {
double sumOfGrades = 0;
boolean isCorrectNumber;
double aGrade = 0;
for (int i = 1; i <= numberOfGrades; i++) {
isCorrectNumber = false;
do {
System.out.print("Enter grade " + i + ": ");
if (!input.hasNextDouble()) {
System.out.println("Error: The grade must be a number.");
input.nextLine();
} else {
aGrade = input.nextDouble();
if (aGrade < 0) {
System.out.println("Error: The grade must be zero or positive.");
} else {
isCorrectNumber = true;
}
}
} while (!isCorrectNumber);
sumOfGrades += aGrade;
}
double averageGrade = (sumOfGrades > 0)? sumOfGrades / numberOfGrades : 0;
return averageGrade;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.