patternjavaMinor
Checking to see if a string is alphabetic
Viewed 0 times
alphabeticcheckingstringsee
Problem
public class Alphabet {
public static void main(String[] args) {
checkAlphabetic("fdsfsfds+");
}
public static boolean checkAlphabetic(String input) {
char[] chars = input.toCharArray();
int count = 0;
for (int i = 0; i = 1) {
System.out.println("alphabetic word");
return true;
} else {
System.out.println("word is not alphabetic");
return false;
}
}
}I know people will say to use regex as it's more efficient but our tutor wanted us to use loops, as we haven't learned about regex yet (old school course).
Solution
It's not harder than this:
The idea is to return
public static boolean checkAlphabetic(String input) {
for (int i = 0; i != input.length(); ++i) {
if (!Character.isLetter(input.charAt(i))) {
return false;
}
}
return true;
}The idea is to return
false as soon as you encounter a character c for which Character.isLetter returns false. If no such, return true since the string does not contain non-letter characters.Code Snippets
public static boolean checkAlphabetic(String input) {
for (int i = 0; i != input.length(); ++i) {
if (!Character.isLetter(input.charAt(i))) {
return false;
}
}
return true;
}Context
StackExchange Code Review Q#150597, answer score: 6
Revisions (0)
No revisions yet.