Checking for digits

Asked by At

I'm trying to figure out this problem. The directions are set hasDigit to true when a three character passCode from a scanner contains a digit.

Code below

import java.util.Scanner;

public class CheckingPasscodes {
   public static void main (String [] args) {
      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.");
      }
   }
}

I've entered in the line hasDigit = Character.isDigit(passCode);

My logic is that character.isDigit is checking the passCode from the scanner, but I keep getting an error.

I've also tried: hasDigit = Character.isDigit(0); and the first test passes, but not the other. From this I assumed that I would have to enter in the string so it would test for anything, not just the character at position 0.

Thanks for the help.

2 Answers

-2
p.bansal On

isDigit() function of Character class excepts either one character or an integer. It does not excepts string , that's why you are getting error. You can modify your code to -

         hasDigit = false;
          passCode = scnr.next();

         for(int i = 0 ;i <passCode.length();i++) {
             hasDigit = Character.isDigit(passCode.charAt(i));
             if(hasDigit)
               break;
         }
          if (hasDigit) {
             System.out.println("Has a digit.");
          }
          else {
             System.out.println("Has no digit.");
          }

this will give you required result.

0
damagedCoda On
for(int i = 0 ;i <passCode.length();i++) {
         hasDigit = Character.isDigit(passCode.charAt(i));
         if (hasDigit) {
             System.out.println("Has a digit.");
             break;
         }
}
if(!hasDigit) {
    System.out.println("Has no digit.");
}

Pity that the answer was revealed but if you are going to spoil the learning process at least try giving the right code :/