java异常只输入字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18712064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 10:23:42  来源:igfitidea点击:

java Exceptions Enter String only

javatry-catch

提问by user2763766

How to catch integer if the user must input String only, no integer and Symbols included to the input? Help me sir for my beginner's report.

如果用户必须只输入字符串,输入中没有包含整数和符号,如何捕获整数?帮我先生做我的初学者报告。

import java.util.*;
public class NameOfStudent {


    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        String name = "";

        System.out.print("Please enter your name: ");
        name = input.nextLine(); // How to express error if the Strin contains
                                //integer or Symbol?...

        name = name.toLowerCase();

        switch(name)
        {
        case "cj": System.out.print("Hi CJ!");
        break;
        case "maria": System.out.print("Hi Maria!");
        break;
        }

    }

}

采纳答案by surender8388

Use this regular expression.

使用这个正则表达式。

Check if a String contains number/symbols etc..

检查字符串是否包含数字/符号等。

boolean result = false;  
Pattern pattern = Pattern.compile("^[a-zA-Z]+$");  
Matcher matcher = pattern.matcher("fgdfgfGHGHKJ68"); // Your String should come here
if(matcher.find())  
    result = true;// There is only Alphabets in your input string
else{  
    result = false;// your string Contains some number/special char etc..
}

Throwing custom exceptions

抛出自定义异常

Throwing custom exceptions in java

在java中抛出自定义异常

Working of a try-catch

try-catch 的工作

try{
    if(!matcher.find()){ // If string contains any number/symbols etc...
        throw new Exception("Not a perfect String");
    }
        //This will not be executed if exception occurs
    System.out.println("This will not be executed if exception occurs");

}catch(Exception e){
    System.out.println(e.toString());
}

I just given a overview, how try-catch works. But you should not use a general "Exception" ever. always use your customized exception for your own exceptions.

我只是概述了 try-catch 的工作原理。但是你永远不应该使用一般的“例外”。始终将您自定义的异常用于您自己的异常。

回答by Ankur Lathi

Use Regexwhich is a sequence of characters that forms a search pattern:

使用Regexwhich 是形成搜索模式的字符序列:

Pattern pattern = Pattern.compile("^[a-zA-Z]*$");
Matcher matcher = pattern.matcher("ABCD");
System.out.println("Input String matches regex - "+matcher.find());

Explanation:

解释:

^         start of string
A-Z       Anything from 'A' to 'Z', meaning A, B, C, ... Z
a-z       Anything from 'a' to 'z', meaning a, b, c, ... z
*         matches zero or more occurrences of the character in a row
$         end of string

If you also want to check for empty string then replace * with +

如果您还想检查空字符串,则将 * 替换为 +



If you want to do it without regexthen:

如果你不想这样做regex

public boolean isAlpha(String name) 
{
    char[] chars = name.toCharArray();

    for (char c : chars) 
    {
         if(!Character.isLetter(c)) 
         {
                return false;
         }
    }

    return true;
}

回答by blackbird014

Once you have the String in your hand, e.g. name you can apply a regexp to it as follows.

一旦您拥有了字符串,例如名称,您就可以按如下方式对其应用正则表达式。

    String name = "your string";
    if(name .matches(".*\d.*")){
        System.out.println("'"+name +"' contains digit");
    } else{
        System.out.println("'"+name +"' does not contain a digit");
    }

Adapt the logic checks to your needs.

根据您的需要调整逻辑检查。

回答by gerrytan

Please be aware that a string can contain numeric character, and it's still a string:

请注意,字符串可以包含数字字符,但它仍然是字符串

String str = "123";

I think what you meant in your question is "How to enforce alphabetical user input, no numeric or symbol", which can be easily done using regular expression

我认为您在问题中的意思是“如何强制按字母顺序输入用户输入,没有数字或符号”,这可以使用正则表达式轻松完成

Pattern pattern = Pattern.compile("^[a-zA-Z]+$"); // will not match empty string
Matcher matcher = pattern.matcher(str);
bool isAlphabetOnly = matcher.find();

回答by Ruchira Gayan Ranaweera

You can change your code as follows.

您可以按如下方式更改代码。

    Scanner input=new Scanner(System.in);
    System.out.print("Please enter your name: ");
    String name = input.nextLine();
    Pattern p=Pattern.compile("^[a-zA-Z]*$");// This will consider your 
                                                input String or not 
    Matcher m=p.matcher(name);
    if(m.find()){
        // your implementation for String.
    } else {
        System.out.println("Name should not contains numbers or symbols ");

    }

Follow this link more about Regex. And test some regex by your self from here.

点击此链接了解更多关于Regex 的信息。并从这里自己测试一些正则表达式。

回答by a dawg

umm..try storing the values in an array..for each single value , use isLetter() and isDigit() ..then construct a new string with that array

嗯..尝试将值存储在数组中..对于每个单个值,使用 isLetter() 和 isDigit() ..然后用该数组构造一个新字符串

use try catch here and see ! i am not used to Pattern class ,use that if thats' simpler

在这里使用 try catch 看看!我不习惯 Pattern 类,如果那更简单,请使用它

回答by jboi

In Java you formulate what the String is allowed to contain in a regular expression. Then you check if the String contains the allowed sequence - and only the allowed sequence.

在 Java 中,您可以制定 String 允许在正则表达式中包含的内容。然后检查 String 是否包含允许的序列 - 并且仅包含允许的序列。

Your code looks like this. I've added a do-while-loop to it:

你的代码看起来像这样。我给它添加了一个 do-while 循环:

    Scanner input = new Scanner(System.in);
    String name = "";

    do { // get input and check for correctness. If not correct, retry
        System.out.print("Please enter your name: ");
        name = input.nextLine(); // How to express error if the String contains
                                //integer or Symbol?...

        name = name.toLowerCase();
    } while(!name.matches("^[a-z][a-z ]*[a-z]?$"));
    // The above regexp allows only non-empty a-z and space, e.g. "anna maria"
    // It does not allow extra chars at beginning or end and must begin and end with a-z

    switch(name)
    {
    case "cj": System.out.print("Hi CJ!");
    break;
    case "maria": System.out.print("Hi Maria!");
    break;
    }

Now you can change the regular expression, e.g. to allow names with asian character sets. Take a look herehow to handle predefined character sets. I was once checking any text for words in any language (and any part of the UTF-8 character set) and ended up with a regular expression like this to find the words in a text: "(\\p{L}|\\p{M})+"

现在您可以更改正则表达式,例如允许使用亚洲字符集的名称。看看这里如何处理预定义的字符集。我曾经检查任何文本中的任何语言(以及 UTF-8 字符集的任何部分)中的单词,并最终使用这样的正则表达式来查找文本中的单词:"(\\p{L}|\\p{M})+"

回答by Maitri

if we want to check that two different user enter same email id while registration.....

如果我们想检查两个不同的用户在注册时输入相同的电子邮件 ID.....

public User updateUsereMail(UserDTO updateUser) throws IllegalArgumentException { System.out.println(updateUser.getId());

公共用户 updateUsereMail(UserDTO updateUser) 抛出 IllegalArgumentException { System.out.println(updateUser.getId());

    User existedUser = userRepository.findOneById(updateUser.getId());
    Optional<User> user = userRepository.findOneByEmail(updateUser.getEmail());
    if (!user.isPresent()) {
        existedUser.setEmail(updateUser.getEmail());
        userRepository.save(existedUser);
    } else {
        throw EmailException("Already exists");
    }

    return existedUser;
}

回答by kumi

    Scanner s = new Scanner(System.in);
    String name;

    System.out.println("enter your name => ");
    name = s.next();

    try{
        if(!name.matches("^[a-zA-Z]+$")){
            throw new Exception("is wrong input!");
        }else{
            System.out.println("perfect!");
        }
    }catch(Exception e){
        System.out.println(e.toString());
    }