如何在Java中设置输入字符的限制?

3
do{
        out.println("\n---------------------------------");
        out.println("---------------------------------");
        out.print("Please type your acces card number: ");

    try{
        card = input.nextInt();

        if(card.length != 10){
            out.println("The number you typed is incorrect");
            out.println("The number must be 10 numbers long");
        continue;
            }
        }   

        catch(InputMismatchException ex){
            }
    }while(true);    

我试图让卡号长度为10位,例如(1234567890),如果用户输入了(123)或(123456789098723),则应该出现错误消息。 card.length似乎不起作用。


或许你可以先尝试接收纯字符串,然后将其解析为整数。 - Jason Hu
1
我支持“将卡号视为字符串”的方法 - 通常来说,卡号不需要进行数学操作,并且可能包含前导零,因此使用字符串实际上是一种合理的表示方式。 - Matt Coubrough
4个回答

3

只需将int更改为String

   String card = input.next();
   if(card.length() != 10){
      //Do something
   }

稍后您可以轻松将其转换为整数

   int value = Integer.parseInt(card);

3

您可以进行更改

if(card.length != 10){

转换为类似于

if(Integer.toString(card).length() != 10){

当然,用户可能输入了。
0000000001

这与1相同。你可以尝试:

String card = input.next(); // <-- as a String

那么

if (card.length() == 10)

最后的内容是:

最终


Integer.parseInt(card)

0
你无法获取 int 的长度。最好将输入作为 String 获取,如果需要的话稍后再转换为 int。您可以在 while 循环中进行错误检查,如果您喜欢短路,您可以让 while 检查也显示您的错误消息:
out.println("\n---------------------------------");
out.println("---------------------------------");
out.print("Please type your access card number: ");

do {
    try {
        card = input.nextLine();
    } catch (InputMismatchException ex) {
        continue;
    }
} while ( card.length() != 10 && errorMessage());

并让您的errorMessage函数返回true,并显示错误消息:

private boolean errorMessage()
{
    out.println("The number you typed is incorrect");
    out.println("The number must be 10 numbers long");
    return true;
}

0
在Java中,你不能获取一个int的长度。查找数字位数最简单的方法是将其转换为String。但是,您也可以进行一些数学运算来确定数字的长度。您可以在这里找到更多信息。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接