Reputation:
i am not able to check the non string value such as a-z and A-Z using public method
Scanner input = new Scanner(System.in);
System.out.print("Enter your First Name: ");
String First_name = input.nextLine();
Scanner last = new Scanner(System.in);
System.out.print("Enter your Last Name: ");
String Last_name = last.nextLine();
here is public method
public static boolean check_non_string_value (String First_name, String Last_name){
// dont know how to check the input here
}
Upvotes: 1
Views: 670
Reputation: 26094
This method valid for a-z and A-Z characters
public static boolean check_non_string_value (String First_name, String Last_name){
if(First_name.matches("[a-zA-Z]+")&&Last_name.matches("[a-zA-Z]+")){
system.out.println("Valid input");
return true;
}
return false;
}
This method valid for all word characters
public static boolean check_non_string_value (String First_name, String Last_name){
if(First_name.matches("\\w")&&Last_name.matches("\\w")){
system.out.println("Valid input");
return true;
}
return false;
}
Upvotes: 1
Reputation: 129507
You can use regular expressions but it's also relatively simple to just loop over each string yourself and use Character.isLetter()
to check each character:
for (char c : firstName.toCharArray()) {
if (!Character.isLetter(c))
return false;
}
for (char c : lastName.toCharArray()) {
if (!Character.isLetter(c))
return false;
}
return true;
Note that I've used more conventional names: firstName
and lastName
. You should always try to follow Java's naming conventions (i.e. use camelCase). Your method name should also be checkNonStringValue
.
With regular expressions, you could do something like:
private static final Pattern letters = Pattern.compile("\\p{Alpha}+");
...
return letters.matcher(firstName).matches() &&
letters.matcher(lastName).matches();
\p{Alpha}
is a pre-defined character class meaning [a-zA-Z]
. See Pattern
for more details.
Upvotes: 3