【问题标题】:How do you make sure user input are integers only?你如何确保用户输入只是整数?
【发布时间】:2014-01-30 17:25:42
【问题描述】:

就概念而言,我做了所有事情。我做了我的课,我的客户课。 作业是制作一个程序,让用户在成绩簿中输入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() + ".");

      }
  }

【问题讨论】:

  • 您的问题是您是否应该记录这一点,或者如何执行?
  • 一种方法是throw一些异常,当用户给出一个非整数然后要么终止程序要么继续执行。
  • 我的问题是如何确保用户输入只是一个整数?

标签: java arrays class loops client


【解决方案1】:

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

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

【讨论】:

  • 谢谢,现在的问题是,对于 else 语句,它会无限次打印 println。
  • 嘿,我的最大值和最小值没有将用户输入限制在 0-100 之间,我该怎么做
  • 甜蜜它输出一次整数错误。现在我发现每次我输入一个超出范围的数字时,它都会接受它。边界是0-100
  • 好的,很抱歉打扰你,但现在代码允许第一个输入是任何内容,而第二个通过无限输入输出错误消息。_例如,_ “请输入10个等级”,我输入了一个错误的数字201它接受它,然后我输入另一个错误的数字它输出Grade must be from 1-100
  • 现在就试试,你又不会纠缠我,这很有趣。
【解决方案2】:

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

【讨论】:

  • 这与在我的课堂上放置扫描仪有什么关系吗?因为我相信条件 integers only 不能使用,除非用户输入一些东西。
【解决方案3】:

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

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

【讨论】:

  • 教授还没有教我们例外。不是你的错,谢谢你的询问。
【解决方案4】:

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

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

【讨论】:

  • 正在查看扫描仪nextInt() 的文档。对于那个很抱歉! +1 会提出与此类似的建议。
【解决方案5】:

查看link,它有解决方案。

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

【讨论】:

  • 但只是第一次出现在 if 子句中。您也应该在 for 子句中使用它。在 for 中,您只使用 getInt(),并没有检查您扫描的下一个值是否是 int。
  • 哦,对不起@peter.petrov,我还以为是 PatGreens 给我回复的!
【解决方案6】:

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

请记住,您的有效数字介于 0 和 100 之间,并且在看到您的代码时不包括 0 和 100,reg ex 将是:

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

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

【讨论】:

  • 不要敲你,但这对于我所学到的来说似乎太复杂了。
  • 实际上看起来老师在你的情况下想要的是像上面提出的@carexcer一样使用Scanner和hasNextInt方法。
猜你喜欢
  • 2018-06-08
  • 1970-01-01
  • 2022-10-22
  • 1970-01-01
  • 2020-07-09
  • 2018-01-22
  • 1970-01-01
  • 1970-01-01
  • 2015-05-17
相关资源
最近更新 更多