Write a program to find out if the string contains only digits.
The long method would be to scan the string and determine whether each character is a digit.
The short but not so good method would be to convert this string to Integer object. If the string has non-digits, the method would throw an exception.
The third method is using regular expression. Java String class has a method called matches() which checks for regular expressions.
String s1 = "123";
if (s1.matches("\\d+"){
/*****/
}
Here \\d meta character indicates digit. + indicates one or more. So we are saying if the string is composed of 1 or more digits - but nothing else, return true.
Here is the complete program to find if the given string contains only digits.
import java.util.Scanner; public class OnlyDigits { public static void main(String args[]) { System.out.println("Enter a string:"); Scanner scanner = new Scanner(System.in); String str = scanner.nextLine(); boolean onlyDigits = str.matches("\\d+"); if(onlyDigits==true) System.out.println("The string contains only digits"); else System.out.println("no"); } }
Comments
Post a Comment