简体   繁体   English

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

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

I've tried to find something on this but have not seen anything related in the past hour of searching. 我试图在此上找到一些东西,但是在过去的一个小时的搜索中没有看到任何相关的东西。 I am looking to throw an error when the user tries to enter a number instead of a String. 我试图在用户尝试输入数字而不是字符串时引发错误。

I've found more than enough resources on how to throw and error when the user enters a string instead of a int, but nothing about the other way. 当用户输入字符串而不是int时,我发现了足够的资源来了解如何引发和出错,但是反之则无所作为。

I'll just make up some code real quick 我将快速编写一些代码

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

        }
    }

Try this: 尝试这个:

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

If it's only the first character you're interested in, you could use a test like this: 如果它只是您感兴趣的第一个字符,则可以使用如下测试:

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

A test on the whole string, as you apparently have found out already, would be: 正如您显然已经发现的那样,对整个字符串进行测试将是:

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

Use the regular expression "^\\\\d" to find out if there are any digits at the start of your string. 使用正则表达式"^\\\\d"找出字符串开头是否有数字。

For example, in order to check if the start of a name is a digit: 例如,为了检查名称的开头是否是数字:

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

Here is a good place to get started on regular expressions: http://www.vogella.com/tutorials/JavaRegularExpressions/article.html 这是开始使用正则表达式的好地方: 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