Abz
Abz

Reputation: 13

How to make program display an error message if the input doesn't start with a letter

Just like what the title says i have been trying to do this for hours.

System.out.print ("Please input the first name: ");
name1 = in.next();

if (name1.substring(0,1).equals("[a-zA-Z]"))
System.out.println("\t" + name1.substring(0,1).toUpperCase()+name1.substring(1).toLowerCase() + "  is in the name list");

else if (name1.substring(0,1).equals("[0-9]"));
System.out.println("error");

This is part of the code that is not working out for me. I dont really know where i went wrong im a beginner at this. With this code whatever I write i get the second System.out.println back which is error. I want the program to display an error message if the string doesnt start with a number. Also, please use the if statement to do that because I couldn't use something I have not covered otherwise I would have searched it.

Upvotes: 1

Views: 1871

Answers (4)

wO_o
wO_o

Reputation: 318

The reason why you get the second print statement all the time is because you've added a ';' after the else if:

Change

else if (name1.substring(0,1).equals("[0-9]"));

To

else if (name1.substring(0,1).equals("[0-9]"))

Remove that semi colon first!

Upvotes: 0

Cat Snacks
Cat Snacks

Reputation: 96

This should do it:

if(!Character.isAlphabetic(name1.charAt(0)) {
    //it's not a letter
}

Upvotes: 4

user3437460
user3437460

Reputation: 17454

Use matches if you want to use REGEX:

if (name1.substring(0,1).matches("[a-zA-Z]"))

equals checks for exact match. It will only be true if your first letter is "[a-zA-Z]" which will never happen.

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201447

I suggest you use Character.isLetter(char), name your variables and define them when you initialize them. Something like

Scanner in = new Scanner(System.in);
System.out.print ("Please input the first name: ");
String firstName = in.next();
if (Character.isLetter(firstName.charAt(0))) {
    // It is a letter.
} else {
    // It is not a letter.
}

Upvotes: 2

Related Questions