Check if String contains only Digit's - Java 2024 - Technical Interview

 Check String contains only Digit's

        Get the input from the user using Scanner class. Then create a method to check the following condition.

1. Check if the string is null or empty, if it is directly return false.

2. Iterate the String using for loop inside the for loop, use the if for condition checking.

3. Condition is check the Digit's only, for this use the Character Wrapper class, in that we have isDigit() method to check the Digit's.

4. This method will return true or false based on it is Digit's or not.

Code :

package com.dinatechy.challange;


import java.util.Scanner;


public class CheckDigitsOnly {

public static void main(String[] args) {

//To check if the String contains only Digit's

Scanner scan = new Scanner(System.in);

String data = scan.next();

scan.close();

boolean isDigits = checkDigits(data);

System.out.println(isDigits ? "Yes it is" : "No it's not");

}


private static boolean checkDigits(String data) {

// " "

if(null == data || data.isEmpty() || data.isBlank())

return false;

int size = data.length();

for(int i=0; i<size; i++) {

if(!Character.isDigit(data.charAt(i))) {

return false;

}

}

return true;

}


}

Scenario 1:

Input :

Enter the mobile number : 9876543210

Output :

Yes it is

Scenario 2:

Input :

Enter the mobile number : 987654321@

Output :

No it's not

Follow us for more Coding Programs like this...

Comments

Popular posts from this blog

Finding Second largest number in Array - Java - TCS - Technical Interview

Checking Character only in String - Java 2024 - MNC - Technical Interview

Object Class in Java | Article | Solution Maker - Blog