How to check if a string contains only digits in java

We know Integer.parseInt(number) will throw NumberFormatException if we are passing any non digit charactors, using this here is one simple example which is checking the given string contains only digit or not.

Example

package com.pretech;
public class NumberCheck {
	
	public static void main(String[] args) {
		System.out.println(isNumber("121221"));
		System.out.println(isNumber("pretech123"));
	}
	  private static boolean isNumber(final String number) {
	        boolean bisNumber = false;
	        if (number == null) {
	            bisNumber = false;
	        }
	        try {
	            Integer.parseInt(number);
	            bisNumber = true;
	        } catch (NumberFormatException ne) {
	            bisNumber = false;
	        }
	        return bisNumber;
	    }
}

Output



true
false

No comments:

Post a Comment

Confusion Matrix + Precision/Recall (Super Simple, With Examples)

  Confusion Matrix + Precision/Recall (Super Simple, With Examples) 1) Binary Classification Setup Binary classification means the model p...

Featured Posts