简体   繁体   English

如何确保用户输入仅是整数?

[英]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;
         }
      }

Chech this link , it has the solution. 点击此链接 ,它有解决方案。

You must use the method hasNextInt() of Scanner . 您必须使用Scanner hasNextInt()方法。

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.

相关问题 如何确保用户仅输入整数类型和大于0的整数? - How do I make sure User input integer type only and integer that is greater than 0? 即使满足两个输出的条件,如何确保仅使用一个输出? - How do you make sure only one output is used even if the criteria are met for two outputs? 您如何使程序等待用户输入? - How do you make a program wait for user input? 对于 Java,如果我想做一个 if 语句以确保输入只包含一个字符,我应该如何进行? - For Java, if I want to do an if statement to make sure the input only takes in one character, how should I proceed? 如何确保输入不是 null 并且只输入了一个字符? - How do I make sure that the input is not null and that only one character is being entered? 如何确保用户仅输入0到10之间的数字? - How do I make sure that the user enters a number between 0 and 10 only? 你如何确保碰撞后 2 个球被移除? - How do you make sure the 2 balls are removed after the collision? 如何确保用户仅输入1和0? - How to make sure the user only inputs 1s and 0s? 如何创建一个由RandomNumber整数组成的数组列表? 爪哇 - How do you make an Arraylist of RandomNumber integers? java 如何在 Jframe 中正确添加整数? - How do you make integers get added properly in Jframe?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM