0

My problem is that I need to throw an exception when the user inputs anything other than an alphabet.

I can't change the fact that I'm using BufferedReader because it's part of an assignment for school. Here is my code:

public static String phoneList(String lastNameInput, String nameInput)
        throws IOException {

    BufferedReader bufferedreader = new BufferedReader(
            new InputStreamReader(System.in));

    try {

        System.out.println("Please input your first name.");
        // User input block
        String input = bufferedreader.readLine();
        nameInput = input;
    } catch (IOException e) {
        System.out.println("Sorry, please input just your first name.");
    }

    try {
        System.out.println("Please input your last name.");
        String input2 = bufferedreader.readLine();
        lastNameInput = input2;
    } catch (IOException e) {
        System.out
                .println("Sorry, please only use letters for your last name.");
    }
    return (lastNameInput + ", " + nameInput);

}

So what method can I use to throw an exception if the user input contains a number, or non-alphabet character?

3
  • 3
    All inputs are strings, pretty much by definition. Commented Nov 5, 2012 at 0:55
  • java lesson on throwing exceptions functionx.com/java/Lesson15.htm Commented Nov 5, 2012 at 0:55
  • There I edited my original post, so it should make more sense now. Commented Nov 5, 2012 at 1:29

2 Answers 2

3

My problem is that I need to throw an exception when the user inputs anything other than string (i.e, an int, float, or double.)

What you are asking doesn't make sense. To illustrate, "12345" is a string. Yes ... IT IS. So if you call readLine() and the line consists of just digits, you will get a string consisting of just digits.

So to solve your problem, after you have read the string, you need to validate it to make sure that it is an acceptable "first name". You could do this a number of ways:

  • The crudest way is to iterate over the string, checking that each character us acceptable.
  • A slightly less crude (but probably wrong) way might be to try to parse the string as an integer of floating point number. (As an exercise, figure out why I said "probably wrong".)
  • The elegant way would be to use java.util.regex.Pattern and a pattern that matches acceptable names, and excludes unwanted stuff like digits, embedded white-space and punctuation.

And as @DanielFischer's comment points out, you need to think carefully about what characters should be acceptable in names. Accents are one example, and others might be cyrillic or chinese characters ... or hyphens.

Sign up to request clarification or add additional context in comments.

6 Comments

Yeah, sorry. What I meant was anything that's a number, because the point of the program to to print a last name, then a first name, but I need an error to stop the user from inputting a number. Also @Daniel Fischer, yeah I know some people have diacritics in their names, but I just got this assigned by a teacher, so blame him.
@TimothyPortelance - "... so blame him" - I wouldn't!!! He/she is simplifying the problem for a programming exercise so that everyone in the class will be able to complete it. I'm simply pointing out the issue to YOU ... so that when YOU have to do this kind of programming in a real-world application you will give the problem due consideration.
Sorry, it's just that his instructions said just block out numbers and non-alphabet characters.
For what it is worth, validating human names is an almost impossible task if you have to take into account all of the linguistic and national variations; e.g. read this: kalzumeus.com/2010/06/17/…
Thank god I don't have to program for every single possible character set in every single language.
|
3

If you mean that the String should only contain alphabets, then use String.matches(regex).

if(bufferedreader.readLine().matches("[a-zA-Z]+")){
System.out.println("user entered string");
}
else {
throw new IOException();
}

"[a-zA-Z]" regex only allows alphabets from a-z or A-Z

or if you dont wanna go with regex. you wouldhave to loop thru the String and check each character if it is not a number.

try{

        System.out.println("Please input your first name.");
        //User input block
        String input = bufferedreader.readLine();
        nameInput = input;
         for(int i=0; i<nameInput.length();i++){
             if(Character.isLetter(nameInput.charAt(i))){
                continue;
              }
              else {
                throw new IOException();
              }
           }
        } catch(IOException e){
            System.out.println("Sorry, please input just your first name.");
        }

7 Comments

André won't be too happy about that regex. People with diacritics in their name exist too.
"If you mean that the String should only contain alphabets" Yeah, sorry this is exactly what I meant, I'll try the code now.
you mean Character#isLetter
@LuiggiMendoza we could call either isLetter() or !isDigit() :)
I don't think so. Any symbol like !@#$%^&*() would pass the !Character#isDigit() validation.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.