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

时间:2014-01-11 18:40:39

标签: java arrays class loops client

我做了一切尽可能的概念。我创建了我的课程和我的客户课程。 作业是制作一个程序,允许用户在成绩册中输入10个等级,并获得最高,最低和平均等级。

我唯一的问题是我想确保用户不能在程序中放入任何不是整数的东西;我可以在我的班级或客户端java doc中添加这样的说明吗?

这是我的班级:

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() + ".");

      }
  }

6 个答案:

答案 0 :(得分:1)

您可能希望分两部分执行此操作 - 您的API应指定它仅使用整数 - 也许处理成绩的方法只接受Integer参数。 String的解析器可以在其Javadocs中指定传递给它的参数不是整数时的作用。您的客户端还应验证输入是否为整数(可能在有效范围内)。如果用户输入不正确,则可能会显示使用手册。

答案 1 :(得分:1)

您可以使用以下代码进行检查。如果你传递的不是数字,它会抛出NumberFormatException

            public static boolean checkIfNumber(String input) {
                try {
                    Integer in = new Integer(input);
                } catch (NumberFormatException e) {
                    return false;
                }
                return true;
            }

答案 2 :(得分:1)

您可以按如下方式更改此部分。这样用户可以输入非整数,但在这种情况下,您将打印出警告,然后您将忽略它们。

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

答案 3 :(得分:1)

在您的客户端的for循环中提示scan.hasNextInt(),而不是在for循环之外。像这样:

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

答案 4 :(得分:1)

Chech this link,它有解决方案。

您必须使用hasNextInt()的方法Scanner

答案 5 :(得分:0)

如果您不想使用例外,您可以始终使用正则表达式匹配来检查字符串中的内容是否对您有效。

请记住,您的有效数字介于0到100之间,并且不包括0和100,您的代码将会出现:reg /将是:

s.matches("[1-9][0-9]{0,1}")

基本上这意味着你将有一个1到9之间的数字作为第一个字符,然后你可以有一个介于0和9之间的字符,这样你就不会在开头允许0( 01无效)和0自身也无效。 100有3个字符,因此无效。