在Java中,您可以将输入限制为只能输入数字或只能输入一定数量的数字吗?

时间:2017-02-11 01:00:06

标签: java

在Java中,您可以使用扫描仪将输入限制在只能输入某些类型(如数字或字母)的位置。您也可以将输入限制为可以输入的一定数量的字符吗?

1 个答案:

答案 0 :(得分:1)

正如评论中所提到的,你不能这样做但是你可以使用类似下面的代码检查输入是否是一个数字并且少于一定数量的字符,提示用户输入是否无效:

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    final int MAX_LENGTH = 4;
    int num = 0;

    System.out.print("Enter a number: ");
    scanner:
    while(scanner.hasNext()) {
      if(scanner.hasNextInt()){
        num = scanner.nextInt();
        if(String.valueOf(num).length() <= MAX_LENGTH) {
          break scanner;
        } else {
          System.out.println("ERROR: Input number was too long");
          System.out.print("Enter a number: ");
        }
      } else {
        System.out.println("ERROR: Invalid Input");
        System.out.print("Enter a number: ");
        scanner.next();
      }
    }
    System.out.println("Valid input! You entered: " + num + ", a number less than or equal to " + MAX_LENGTH + " characters long");
  }
}

试试here!

使用示例:

Enter a number:  123sdf
ERROR: Invalid Input
Enter a number:  1234234
ERROR: Input number was too long
Enter a number:  1234
Valid input! You entered: 1234, a number less than or equal to 4 characters long