繁体   English   中英

当用户输入数字而不是字符串时显示错误

[英]Display an error when user enters a number instead of a string

我试图在此上找到一些东西,但是在过去的一个小时的搜索中没有看到任何相关的东西。 我试图在用户尝试输入数字而不是字符串时引发错误。

当用户输入字符串而不是int时,我发现了足够的资源来了解如何引发和出错,但是反之则无所作为。

我将快速编写一些代码

import java.util.Scanner;

public class ayylmao {

    public static void main(String[] args) {
            Scanner scan = new Scanner(System.in);
            System.out.println("Enter your first name");
            String AyyLmao = scan.nextLine();
            System.out.println("Your first name is " + AyyLmao);
/*
Want it to say something like "Error: First character must be from the alphabet!" if the user tries to enter a number.
*/

        }
    }

尝试这个:

public static boolean isIntegerParseInt(String str) {
    try {
        Integer.parseInt(str);
        return true;
    } catch (NumberFormatException nfe) {}
    return false;
}

如果它只是您感兴趣的第一个字符,则可以使用如下测试:

if (AyyLmao.charAt(0) >= '0' && AyyLmao.charAt(0) <= '9'){
  /* complain here */
}

正如您显然已经发现的那样,对整个字符串进行测试将是:

try{
  Integer.parseInt(AyyLmao);
  /* complain here */
} catch(NumberFormatException ex){
  /* this would be OK in your case */
}

使用正则表达式"^\\\\d"找出字符串开头是否有数字。

例如,为了检查名称的开头是否是数字:

String regex = "^\\d";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(yourInput);
if(m.find()) {
   // Your input starts with a digit
}

这是开始使用正则表达式的好地方: http : //www.vogella.com/tutorials/JavaRegularExpressions/article.html

private static String acceptName() {
        // TODO Auto-generated method stub
        Boolean flag = Boolean.TRUE;
        String name = "";
        while (flag) {
            Scanner scan = new Scanner(System.in);
            System.out.println("enter name : ");
            name = scan.nextLine();
            try {
                Integer no = Integer.parseInt(name);
                System.out.println("you have entered number....");
            } catch (NumberFormatException e) {
                flag = Boolean.FALSE;

            }
        }
        return name;

    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM