-1

so I am running this in the most recent build of Eclipse. and for some reason, neither me nor my teacher can figure out why this boolean is not changing

This is the code

String value = null;
boolean matching = false;
String regex = "^[a-zA-Z]$";
Scanner input = new Scanner(System.in);
value = input.next();

if (value.matches(regex))
{
    matching = true;
}
else
{
    System.out.println("Name is incorrect, please try again");
}


System.out.println(matching);
System.out.println(value);

1 Answers1

1

By specifying the regex ^[a-zA-Z]$, you are matching single letter inputs (for eg. "a", "d" "F") ... since you input multicharacter string, it wouldn't match

In order to match strings of length>=1 you could use the + operator in regexes, like so,

^[a-zA-Z]+$
mettleap
  • 1,390
  • 8
  • 17