如何在Java中限制/约束用户输入?

时间:2016-02-16 02:02:35

标签: java user-input

如果用户在控制台中键入三个以上的整数,我希望显示一条错误消息。因此,如果控制台说"键入三个整数"并且用户键入123 244 242,无论数字大小如何,它都应该没有问题。但是,如果用户键入123 244 242 442,那么当他们按下运行时,我希望显示一条错误消息。但不完全确定如何解决这个问题。

这是一个简单的程序:

$ bazel build -c opt //tensorflow/tools/pip_package:build_pip_package

# To build with GPU support: 
$ bazel build -c opt --config=cuda //tensorflow/tools/pip_package:build_pip_package

$ bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg

# The name of the .whl file will depend on your platform. 
$ pip install /tmp/tensorflow_pkg/tensorflow-0.5.0-cp27-none-linux_x86_64.whl

谢谢

1 个答案:

答案 0 :(得分:0)

int firstInt = userInput.nextInt();
int secondInt = userInput.nextInt();
int thirdInt = userInput.nextInt();
char run = userInput.next().charAt(0);
if(userInput.hasNext())
{
   System.out.println("Error, you need 3 numbers only, and a char");
   userInput.nextLine(); //clears the rest of the line

}

给出一个镜头,看看它是怎么回事。我建议在while循环中使用它,这样它就会继续为数字启动,直到它完全没有错误。

public static void main(String[] args)
{
   boolean getNumbers = true;
   int firstInt, secondInt, thirdInt;
   Scanner userInput = new Scanner(System.in);
   while(getNumbers)
   {
      firstInt = userInput.nextInt();
      secondInt = userInput.nextInt();
      thirdInt = userInput.nextInt();
      char run = userInput.next().charAt(0);
      if(userInput.hasNext())
      {
         System.out.println("Error message here");
         userInput.nextLine(); //clear the rest of line
         firstInt = secondInt = thirdInt = 0;
         run = '';
      }
      else
      {
         getNumbers = false;
      }
   }
   //do calculations with numbers here
}