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

时间:2015-02-13 06:29:41

标签: java 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.
*/

        }
    }

4 个答案:

答案 0 :(得分:0)

试试这个:

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

答案 1 :(得分:0)

如果它只是你感兴趣的第一个角色,你可以使用这样的测试:

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 */
}

答案 2 :(得分:0)

使用正则表达式"^\\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

答案 3 :(得分:0)

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;

    }
相关问题