1

在java中,是否可以检查一个字符串上是否有特殊字符或字母,如果是则抛出异常?

类似这样的东西,但使用 try/catch

/** Get and Checks if the ssn is valid or not **/
    private String getSSN(){
        String tempSSN;
        tempSSN = scan.nextLine();
        if(tempSSN.matches("^.*[^a-zA-Z ]{9}.*$") == false){
            System.out.print("enter a valid SSN without spaces or dashes.");
            tempSSN= scan.nextLine();
        }
        return tempSSN;
    }
4

2 回答 2

1

如果你可以在没有异常处理的情况下做到这一点,那么你就没有明显的理由为什么要使用try-catch块。但是如果你想抛出一个异常,则不必使用 try-catch 块。您可以使用throw.

    if(something) {
        throw new SomeAppropriateException("Something is wrong");
    }

catch如果要捕获异常并记录任何错误或消息并继续执行,则可以使用块。或者当您想抛出其他有意义的异常时捕获异常。

于 2013-01-18T05:35:53.893 回答
0

我会将字符导入到字符数组中,然后使用循环检查每个字符是否存在要为其抛出异常的字符类型。

下面的一些 sudo 代码:

private String getSSN(){
    String tempSSN = scan.nextLine();

    try {
    char a[] = tempSSN.toCharArray();

    for (int i = 0; i < a.length(); i++) {
        if(a[i] != ^numbers 0 - 9^) {      //sudo code here. I assume you want numbers only.
           throw new exceptionHere("error message");   // use this to aviod using a catch. Rest of code in block will not run if exception is thrown.
    }

    catch (exceptionHere) {      // runs if exception found in try block
        System.out.print("enter a valid SSN without spaces or dashes.");
        tempSSN= scan.nextLine();
    }
    return tempSSN;
}

我还会考虑在长度不是 9 个字符的数组上运行 if 。我假设您正在尝试捕获始终为 9 个字符的 ssn。

if (a.length != 9) {
   throw ....
}

您可以在没有 try/catch 的情况下执行此操作。如果他们第二次输入无效的 ssn,上述内容将中断。

    private String getSSN(){
    String tempSSN = scan.nextLine();

    char a[] = tempSSN.toCharArray();
    boolean marker;

    for (int i = 0; i < a.length(); i++) {
        if(a[i] != ^numbers 0 - 9^) {      //sudo code here. I assume you want numbers only.
           boolean marker = false;
    }

    while (marker == false) {
        System.out.print("enter a valid SSN without spaces or dashes.");
        tempSSN = scan.nextLine();
        for (int i = 0; i < a.length(); i++) {
              if(a[i] != ^numbers 0 - 9^) {      //sudo code here. I assume you want numbers only.
                  marker = false;
              else 
                  marker = true;
    }
    }
    return tempSSN;
}

您可以选择以某种方式使用 contains 方法,我确信。

boolean marker = tempSSN.contains(i.toString());  // put this in the for loop and loop so long as i < 10; this will go 0 - 9 and check them all.
于 2013-01-18T06:40:27.210 回答