在Java中,您可以将输入限制为只能输入数字或只能输入一定数量的数字吗? [英] In Java can you limit the input to where only a number can be entered or only a certain amount of numbers can be entered?

查看:3214
本文介绍了在Java中,您可以将输入限制为只能输入数字或只能输入一定数量的数字吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Java can you limit the input using the scanner to where only a certain types such as numbers or letters can be entered. Also can you limit input to a certain amount of characters that can be entered?

推荐答案

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

As mentioned in the comments you cannot do that however you could check if the input was a number and less than a certain amount of character using something like the code below, prompting the user if their input is invalid:

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

尝试这里!

示例用法:

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

这篇关于在Java中,您可以将输入限制为只能输入数字或只能输入一定数量的数字吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆