You could use:
if (Character.isLetter(character.charAt(0))){
....
Answer from Reimeus on Stack OverflowYou could use:
if (Character.isLetter(character.charAt(0))){
....
You could use the existing methods from the Character class. Take a look at the docs:
http://download.java.net/jdk7/archive/b123/docs/api/java/lang/Character.html#isDigit(char)
So, you could do something like this...
String character = in.next();
char c = character.charAt(0);
...
if (Character.isDigit(c)) {
...
} else if (Character.isLetter(c)) {
...
}
...
If you ever want to know exactly how this is implemented, you could always look at the Java source code.
I have always been having issues with finding ways to stop the wrong inputs from being set in variables. I just found out about testing with the use of isLetter and isDigit. I was wondering if I have to convert the inputs to characters or will those two methods accept string and integer?
This should work.
public boolean containsBothNumbersAndLetters(String password) {
boolean digitFound = false;
boolean letterFound = false;
for (char ch : password.toCharArray()) {
if (Character.isDigit(ch)) {
digitFound = true;
}
if (Character.isLetter(ch)) {
letterFound = true;
}
if (digitFound && letterFound) {
// as soon as we got both a digit and a letter return true
return true;
}
}
// if not true after traversing through the entire string, return false
return false;
}
It's hard to help you do it without giving you all the code to do it, since it's so short.
Anyway for a start, since you need at least one letter and at least one digit, you're going to need two flags, two booleans, which will initially be false. You can iterate through each char in ininitialPassword by using a foreach loop:
for (char c : initialPassword.toCharArray())
And then all you have to do is check at each iteration if c is possibly a letter or a digit, and set the corresponding flag if so. Once the loop terminates, if both the flags are set, then your password is valid. This is what your code could look like:
boolean bHasLetter = false, bHasDigit = false;
for (char c : initialPassword.toCharArray()) {
if (Character.isLetter(c))
bHasLetter = true;
else if (Character.isDigit(c))
bHasDigit = true;
if (bHasLetter && bHasDigit) break; // no point continuing if both found
}
if (bHasLetter && bHasDigit) { /* valid */ }