Reputation: 17
Kepp getting an error when using Character.isDigit()
I've looked it up elsewhere and tested it fine there but I keep running into this error here.
Scanner scnr = new Scanner(System.in);
boolean hasDigit;
String passCode;
hasDigit = false;
passCode = scnr.next();
hasDigit = Character.isDigit(passCode);
if (hasDigit) {
System.out.println("Has a digit.");
}
else {
System.out.println("Has no digit.");
}
Expect true or false depending on scanner input. Keep getting this error thrown at me:
CheckingPasscodes.java:12: error: no suitable method found for isDigit(String)
hasDigit = Character.isDigit(passCode);
^
method Character.isDigit(char) is not applicable
(argument mismatch; String cannot be converted to char)
method Character.isDigit(int) is not applicable
(argument mismatch; String cannot be converted to int)
Upvotes: 0
Views: 1704
Reputation: 1
I found this worked for me. I set each specified index in the string to a character value using charAt(). From there I created an if statement that would set hasDigit to true if any of the char variables had a number, using Character.isDigit() enter image description here
Upvotes: 0
Reputation: 11
The error is that hasDigit = Character.isDigit(passCode);
Character.isDigit()
expects a character as an argument but you passing String.
So correct this convert the String to char.
you can try
Scanner scnr = new Scanner(System.in);
boolean hasDigit;
char passCode;
hasDigit = false;
passCode = scnr.next().charAt(0);
hasDigit = Character.isDigit(passCode);
if (hasDigit) {
System.out.println("Has a digit.");
}
else {
System.out.println("Has no digit.");
}
Upvotes: 1
Reputation: 699
The Scanner.next method will return whole tokens (usually words) from the input stream. These words are Strings. The Character.isDigit function requires a char as input, not a String.
You could loop over the word, get each letter as a char and test them:
for (int i = 0; i < passCode.length(); i++){
char c = passCode.charAt(i);
if (Character.isDigit(c)) {
hasDigit = true;
}
}
Upvotes: 0
Reputation: 11832
The method Character.isDigit()
takes a char
as input - you are trying to pass it a String
.
The error described what the problem is:
argument mismatch; String cannot be converted to char
Upvotes: 7