[英]How do you make sure user input are integers only?
I did everything as far as concepts. 我做了所有关于概念的事情。 I made my class, and my client class. 我上了我的课,也上了我的客户课。 The assignment is to make a program that allows the user to input 10 grades into a gradebook, and get the max, min, and average grade of class. 作业是制作一个程序,该程序允许用户将10个成绩输入到成绩簿中,并获得班级的最高,最低和平均成绩。
My only problem is I want to make sure the user cannot put anything in the program that is not an integer; 我唯一的问题是我要确保用户不能在程序中放入非整数的任何内容; do I put instructions like that in my class or client java doc? 在类或客户端Java文档中放置类似的说明?
This is my class: 这是我的课:
import java.util.Arrays;
public class ExamBook{
int grades[];
int classSize;
int MIN = 0;
int MAX = 100;
public ExamBook(int[] gradeBook)
{
classSize = 10;
//instantiate array with same length as parameter
grades = new int[gradeBook.length];
for ( int i = 0; i <= gradeBook.length-1; i++ )
{
grades[i] = gradeBook[i];
}
Arrays.sort(grades);
}
//setter, or mutator
public void setClassSize( int newClass )
{
classSize = newClass;
}
//get return method
public int getClassSize()
{
return classSize;
}
//calculate highest grade
public int calculateMaxGrade()
{
int max = grades[0]; //assuming that the first index is the highest grade
for ( int i = 0; i <= grades.length - 1; i++ )
{
if ( grades[i] > max )
max = grades[i]; //save the new maximum
}
return max;
}
//calculate lowest grade
public int calculateMinGrade()
{
int min = grades[0]; //assuming that the first element is the lowest grade
for ( int i = 0; i <= grades.length - 1; i++ )
{
if ( grades[i] < min)
min = grades[i]; //save the new minimum
}
return min;
}
//calculate average
public double calculateAverageGrades()
{
double total = 0;
double average = 0;
for ( int i = 0; i < grades.length; i++ )
{
total += grades[i];
}
average = total/grades.length;
return average;
}
//return an assorted array
public int[] assortedGrades()
{
Arrays.sort(grades);
return grades;
}
//return printable version of grades
@Override
public String toString()
{
String returnString = "The assorted grades of the class in ascending order is this: " + "\t";
for ( int i = 0; i <= grades.length - 1; i++ )
{
returnString += grades[i] + "\t";
}
returnString += " \nThe class average is a/an " + calculateAverageGrades() + "." + "\nThe highest grade in the class is " + calculateMaxGrade() + "." + "\nThe lowest grade in the class is " + calculateMinGrade() + ".";
returnString += "\n";
return returnString;
}
}
**This is my client:**
import java.util.Scanner;
import java.util.Arrays;
public class ExamBookClient
{
public static ExamBook classRoom1;
public static void main( String[] args)
{
int MAX = 100;
int MIN = 0;
Scanner scan = new Scanner(System.in);
//create array for testing class
int[] grading = new int [10];
System.out.println("Please enter 10 grades to go into the exam book.");
if(scan.hasNextInt())
{
for (int i = 0; i < grading.length; i++)
{
int x = scan.nextInt();
if( x>MIN && x<MAX)
{
grading[i] = x;
}
}
}
classRoom1 = new ExamBook (grading);
System.out.println("The classroom size is " + classRoom1.getClassSize() + "."
+ "\n" + classRoom1.toString() + ".");
}
}
You might want to do this in two parts - your API should specify that it works with only integers - perhaps the method which processes the grades will accept Integer arguments only. 您可能希望分两部分进行此操作-您的API应该指定它仅适用于整数-也许处理成绩的方法将仅接受Integer参数。 The parser of the String can specify in its Javadocs what it does when the argument passed to it is not an integer. 字符串的解析器可以在其Javadocs中指定当传递给它的参数不是整数时执行的操作。 You client should also validate that the input is an integer (maybe within the valid range). 您的客户还应验证输入是否为整数(可能在有效范围内)。 If the user input is incorrect, then maybe it can display a usage manual. 如果用户输入不正确,则可能会显示使用手册。
You can check using the below code. 您可以使用以下代码进行检查。 If you pass other than number it would throw NumberFormatException 如果传递的不是数字,则将引发NumberFormatException
public static boolean checkIfNumber(String input) {
try {
Integer in = new Integer(input);
} catch (NumberFormatException e) {
return false;
}
return true;
}
You can change this part as follows. 您可以如下更改此部分。 This way the user can enter non-integers but in those cases you will print out warnings and you will ignore them. 这样,用户可以输入非整数,但是在这种情况下,您将打印出警告,而忽略它们。
System.out.println("Please enter 10 grades to go into the exam book.");
int i = 0;
int x = -1;
while (scan.hasNext() && i < 9) {
String sx = scan.next();
try {
x = Integer.parseInt(sx);
i++;
if (x > MIN && x < MAX) {
grading[i] = x;
}
} catch (NumberFormatException e) {
System.out.println("Not an integer.");
}
}
classRoom1 = new ExamBook(grading);
Prompt for scan.hasNextInt()
in your for loop of your client instead of outside the for loop. 在客户端的for循环中而不是在for循环之外提示scan.hasNextInt()
。 Like this: 像这样:
boolean failed = false;
for (int i = 0; i < grading.length; i++)
{
if (failed)
scan.nextLine();
failed = false;
if (scan.hasNextInt()) {
int x = scan.nextInt();
if(x >= MIN && x <= MAX)
{
grading[i] = x;
} else {
System.out.println("Grade must be from 0-100!");
i--;
continue;
}
} else {
// jump back to the start of this iteration of the loop and re-prompt
i--;
System.out.println("Number must be an int!");
failed = true;
continue;
}
}
If you do not want to use exceptions you can always use a Regex match to check that what you have in the string is a number valid for you. 如果您不想使用异常,则可以始终使用正则表达式匹配项来检查字符串中包含的内容对您有效。
Bearing in mind that your valid numbers are between 0 and 100, and 0 and 100 are not included seeing you code, the reg ex will be: 请记住,您的有效数字在0到100之间,并且在看到代码时不包括0到100,因此正则表达式为:
s.matches("[1-9][0-9]{0,1}")
Basically what this means is that you are going to have a character that is a number between 1 and 9 as first char, and then you could have one between 0 and 9, this way you do not allow 0 at the beginning (01 is not valid) and 0 by it self is also not valid. 基本上,这意味着您将拥有一个介于1到9之间的数字作为第一个字符,然后您可以拥有一个介于0到9之间的数字,这样一来您就不允许在开头添加0(01不是有效),并且0本身也是无效的。 100 has 3 chars so is not valid neither. 100个字符数为3,因此同样无效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.