java异常仅输入字符串

java异常仅输入字符串,java,try-catch,Java,Try Catch,如果用户必须只输入字符串,而输入中不包含整数和符号,如何捕获整数?先生,帮我写初学者报告 import java.util.*; public class NameOfStudent { public static void main(String[] args) { Scanner input = new Scanner(System.in); String name = ""; System.out.print("Please

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

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;
        }

    }

}

使用这个正则表达式

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

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..
}
引发自定义异常

试捕工作

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());
}

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

使用
Regex
,它是一个字符序列,形成搜索模式:

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

^         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
如果还想检查空字符串,则将*替换为+


如果要在不使用正则表达式的情况下执行此操作,请执行以下操作:

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

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

    return true;
}

一旦您手中有了字符串,例如name,您就可以对其应用regexp,如下所示

    String name = "your string";
    if(name .matches(".*\\d.*")){
        System.out.println("'"+name +"' contains digit");
    } else{
        System.out.println("'"+name +"' does not contain a digit");
    }
    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 ");

    }

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

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

String str = "123";
我想你在问题中的意思是“如何强制用户按字母顺序输入,而不是数字或符号”,这可以通过正则表达式轻松实现

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

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

    String name = "your string";
    if(name .matches(".*\\d.*")){
        System.out.println("'"+name +"' contains digit");
    } else{
        System.out.println("'"+name +"' does not contain a digit");
    }
    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 ");

    }

请点击此链接了解更多信息。然后自己从中测试一些正则表达式。

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

在这里试试看!
我不习惯模式类,如果Java中的模式类更简单,那么就用它来定义正则表达式中允许包含的字符串。然后检查字符串是否包含允许的序列,并且只包含允许的序列

您的代码如下所示。我在其中添加了一个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;
    }

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

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

公共用户updateUsereMail(UserDTO updateUser)引发IllegalArgumentException{ System.out.println(updateUser.getId())

User existedUser=userRepository.findOneById(updateUser.getId());
可选用户=userRepository.findOneByEmail(updateUser.getEmail());
如果(!user.isPresent()){
setEmail(updateUser.getEmail());
userRepository.save(existedUser);
}否则{
抛出EmailException(“已存在”);
}
返回现有用户;
}

看看这个,您在“^[a-zA-Z]*$”中使用了“*”。因此,即使它是一个像“”这样的空字符串,它也会说它有一个匹配项。我认为name不能是空字符串。@surender8388:OP对空字符串没有任何问题。他只想检测数字和特殊符号。似乎很难解释2我的同学先生,我可以在try-catch异常中执行吗?有没有办法我可以使用try-catch异常来处理此问题?为什么要抛出异常?请查看链接,尝试使用自定义异常,并将其放在您的else部分。对不起,先生,我们的课讲的是最后一次尝试接球!但我的任务是讨论当需要字符串时,如果输入的数据包含整数,它是如何工作的。我已经放弃了,不知道该做什么…我只是给了一个概述,如何尝试捕捉工程。但是你永远不应该使用一般的“例外”。对于您自己的异常,请始终使用自定义异常。是否有任何方法可以使用try-catch异常来解决此问题,先生?但为什么?没有解释,这只是垃圾,不是答案。这将是一个可怕的鲁布戈德伯格代码。我会对写这种讽刺的人大喊大叫??不太熟悉鲁比·戈德伯格德。但快速的谷歌搜索让我发现了一些与卓越创意有关的东西;)抱歉,如果这听起来很刺耳,但已经处理了无法维护的代码(实际上我写的一些代码,甚至会因为我自己断了的手臂而打自己),这是我的一个非常敏感的地方…我已经做了,先生,但我的教授希望我将其作为“尝试-捕获”例外进行讨论。。抱歉,但是假设pattern类不在那里,或者有人从未偶然发现过它,或者有人对java非常陌生,那么这个方法是非常合理的。。