带有nextLine输入的try / catch语句

时间:2013-10-10 04:47:20

标签: java string exception-handling

这里我有一个简单的try / catch语句,用于输入客户名和姓的字符串。但是,如果输入一个数字或者用户输入任何其他非文本字符,我需要抛出异常(因为名称只包含文本)。问题是字符串确实接受任何字符而不仅仅是文本。如果用户输入除文本之外的任何内容,我怎样才能执行catch?

public void Customer ()
    {
        //Variables for Customer method
        String firstName;
        String lastName;
        int customerNumber;
        boolean end = false;

        /* Reads input from user
         * Stores customers first and last name into the variable name
        */
        while(end == false)
        {
        try
            {
                System.out.println("Enter customers full name" );
                firstName = input.nextLine();

                System.out.println("Enter customers last name");
                lastName = input.nextLine();
                end = true;
            }

        catch (InputMismatchException ime)
        {
            end = false;
            System.out.println("Invalid input. You must enter the customers name. Please try again: ");
            input.next();
        }
        }   
    }

3 个答案:

答案 0 :(得分:0)

制作一个不在名称标准中的字符串arrayList,请执行以下操作:

ArrayList< String>arrayList=new ArrayList<String>();
    arrayList.add("?");
    //add other String
    String input ="some text";
    for(int i=0;i<arrayList.size();i++){
        if(input.contains(arrayList.get(i)))
    input=input.replace(arrayList.get(i), "");
    }

或者你可以摆脱替换部分,如果情况属实,请他或她再试一次

答案 1 :(得分:0)

您可以制作自定义例外

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

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

return true;

}

class InvalidException extends Exception {

    InvalidException() {
    }

    InvalidException(String message) {

  super(message);
    }

    InvalidException(String message, Throwable cause) {

  super(message, cause);
    }
}

public void Customer()     {         // Customer方法的变量         String firstName;         String lastName;         int customerNumber;         boolean end = false;

    while(end == false)
    {
    try
        {
            System.out.println("Enter customers full name" );
            firstName = input.nextLine();

            System.out.println("Enter customers last name");
            lastName = input.nextLine();
    if(isAplha(lastname)){

    }
    else
    {
    throw new InvalidException("Your message here");
    }
            end = true;
        }

    catch (InputMismatchException ime)
    {
        end = false;
        System.out.println("Invalid input. You must enter the customers name. Please try again: ");
        input.next();
    }
    }   
}

答案 2 :(得分:0)

如果正则表达式现在看起来太高,你可以使用一个字符数组来表示字符串...... 对于每个字符数组条目,您可以检查with isNumber() , isDigit and so on. .. 然而,当我之前推荐过这个答案时,一位资深成员说 - “如果他的右手写下这段代码,他会用左手击败自己的右手”:P