Showing posts with label Digits. Show all posts
Showing posts with label Digits. Show all posts

Saturday, 12 November 2022

Check whether string contain only digits or not in Java

Write a function that takes a string as input and return true, if the string contain only digits, else false.

 

Signature

public static boolean hasOnlyDigits(final String str)

Find the below working application.


StringDigitsCheck.java

package com.sample.app.strings;

import java.util.regex.Pattern;

public class StringDigitsCheck {

	private static final Pattern ONLY_DIGITS_PATTERN = Pattern.compile("\\d+");

	/**
	 * 
	 * @param str
	 * 
	 * @return true, if the string contain only digits, else false.
	 */
	public static boolean hasOnlyDigits(final String str) {

		if (str == null || str.isEmpty()) {
			return false;
		}

		return ONLY_DIGITS_PATTERN.matcher(str).matches();
	}

	public static void main(String[] args) {
		String str1 = null;
		String str2 = "Hello";
		String str3 = "122324";
		String str4 = "32453\n";

		System.out.println("is str1 contain only digits : " + hasOnlyDigits(str1));
		System.out.println("is str2 contain only digits : " + hasOnlyDigits(str2));
		System.out.println("is str3 contain only digits : " + hasOnlyDigits(str3));
		System.out.println("is str4 contain only digits : " + hasOnlyDigits(str4));
	}

}

Output

is str1 contain only digits : false
is str2 contain only digits : false
is str3 contain only digits : true
is str4 contain only digits : false


 

Previous                                                 Next                                                 Home

Monday, 29 March 2021

Bean validation: Digits: Number must be within accepted range

 

If you add @Digits annotation on any number, then the number must be within accepted range.

 

Example

@Digits(integer = 9, fraction = 2)

private double salary;

 

What are the supported types?

a.   byte

b.   short

c.    int

d.   long

e.   Byte

f.     Short

g.   Integer

h.   Long

i.     BigDecimal

j.     BigInteger

k.    CharSequence

 

Note: As per specification double, float is not supported due to rounding errors. Some providers may provide some approximative support

 

Where can I apply this annotation?

a.   METHOD,

b.   FIELD,

c.    ANNOTATION_TYPE,

d.   CONSTRUCTOR,

e.   PARAMETER,

f.     TYPE_USE

 

Find the below working application.

 

Employee.java

package com.sample.model;

import javax.validation.constraints.Digits;

public class Employee {

	private int id;

	private String name;

	/*
	 * numeric value out of bounds (<9 digits>.<2 digits> expected)
	 */
	@Digits(integer = 9, fraction = 2)
	private double salary;

	public Employee(int id, String name, double salary) {
		this.id = id;
		this.name = name;
		this.salary = salary;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public double getSalary() {
		return salary;
	}

	public void setSalary(double salary) {
		this.salary = salary;
	}

}

 

Test.java

package com.sample.test;

import java.util.Set;

import javax.validation.*;
import javax.validation.ValidatorFactory;

import com.sample.model.Employee;

public class Test {
	private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
	private static Validator validator = validatorFactory.getValidator();

	private static void validateBean(Employee emp) {
		System.out.println("************************************");
		Set<ConstraintViolation<Employee>> validationErrors = validator.validate(emp);

		if (validationErrors.size() == 0) {
			System.out.println("No validation errors....");
		}

		for (ConstraintViolation<Employee> violation : validationErrors) {
			System.out.println(violation.getPropertyPath() + "," + violation.getMessage());
		}
		System.out.println("");
	}

	public static void main(String args[]) {

		Employee emp1 = new Employee(1, "Krishna", 1234567890);
		System.out.println("Validation errors on bean emp1");
		validateBean(emp1);

		Employee emp2 = new Employee(2, "Siva", 23456789.23);
		System.out.println("Validation errors on bean emp2");
		validateBean(emp2);
	}
}

Output

Validation errors on bean emp1
************************************
salary,numeric value out of bounds (<9 digits>.<2 digits> expected)

Validation errors on bean emp2
************************************
No validation errors....

 

 

Previous                                                    Next                                                    Home

Saturday, 11 April 2020

Extract digits from a string or text

Approach 1: Check each character whether it is a digit or not.
public static final String getDigits_Approach1(String str) {
         if (str == null || str.isEmpty()) {
                  return str;
         }

         StringBuilder stringBuilder = new StringBuilder();

         for (int i = 0; i < str.length(); i++) {
                  if (Character.isDigit(str.charAt(i))) {
                           stringBuilder.append(str.charAt(i));
                  }
         }

         return stringBuilder.toString();
}

Approach 2: Using Regular Expression.
public static final String getDigits_Approach2(String str) {
         if (str == null || str.isEmpty()) {
                  return str;
         }

         return str.replaceAll("\\D+", "");
}

StringUtil.java
package com.smaple.app.utils;

public class StringUtil {

 public static String getDigits_Approach1(String str) {
  if (str == null || str.isEmpty()) {
   return str;
  }

  StringBuilder stringBuilder = new StringBuilder();

  for (int i = 0; i < str.length(); i++) {
   if (Character.isDigit(str.charAt(i))) {
    stringBuilder.append(str.charAt(i));
   }
  }

  return stringBuilder.toString();
 }

 public static String getDigits_Approach2(String str) {
  if (str == null || str.isEmpty()) {
   return str;
  }

  return str.replaceAll("\\D+", "");
 }
}


StringUtilTest.java

package com.sample.app.utils;

import static org.junit.Assert.*;

import org.junit.Test;

import static com.smaple.app.utils.StringUtil.getDigits_Approach1;
import static com.smaple.app.utils.StringUtil.getDigits_Approach2;

public class StringUtilTest {

 @Test
 public void inputIsNull() {
  String text = null;
  
  String result1 = getDigits_Approach1(text);
  String result2 = getDigits_Approach2(text);
  
  assertNull(result1);
  assertNull(result2);
 }
 
 @Test
 public void inputIsEmpty() {
  String text = "";
  
  String result1 = getDigits_Approach1(text);
  String result2 = getDigits_Approach2(text);
  
  assertEquals(text, result1);
  assertEquals(text, result2);
 }
 
 @Test
 public void inputIsNotEmpty() {
  String text = "a12B34)(*1";
  String expected = "12341";
  
  String result1 = getDigits_Approach1(text);
  String result2 = getDigits_Approach2(text);
  
  assertEquals(expected, result1);
  assertEquals(expected, result2);
 }
}


You may like

Sunday, 16 June 2019

Bean validation: Digits: Number must be within accepted range

If you add @Digits annotation on any number, then the number must be within accepted range.

What are the supported types?
a.   byte,
b.   short,
c.    int,
d.   long,
e.   Byte,
f.     Short,
g.   Integer,
h.   Long,
i.     BigDecimal,
j.     BigInteger,
k.    CharSequence

Note: As per specification double, float is not supported due to rounding errors. Some providers may provide some approximative support

Where can I apply this annotation?
a.   METHOD,
b.   FIELD,
c.    ANNOTATION_TYPE,
d.   CONSTRUCTOR,
e.   PARAMETER,
f.     TYPE_USE

Find the below working application.

Employee.java
package com.sample.model;

import javax.validation.constraints.Digits;

public class Employee {

 private int id;

 private String name;

 /*
  * numeric value out of bounds (<9 digits>.<2 digits> expected)
  */
 @Digits(integer = 9, fraction = 2)
 private double salary;

 public Employee(int id, String name, double salary) {
  this.id = id;
  this.name = name;
  this.salary = salary;
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public double getSalary() {
  return salary;
 }

 public void setSalary(double salary) {
  this.salary = salary;
 }

}


Test.java
package com.sample.test;

import java.util.Set;

import javax.validation.*;
import javax.validation.ValidatorFactory;

import com.sample.model.Employee;

public class Test {
 private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
 private static Validator validator = validatorFactory.getValidator();

 private static void validateBean(Employee emp) {
  System.out.println("************************************");
  Set<ConstraintViolation<Employee>> validationErrors = validator.validate(emp);

  if (validationErrors.size() == 0) {
   System.out.println("No validation errors....");
  }

  for (ConstraintViolation<Employee> violation : validationErrors) {
   System.out.println(violation.getPropertyPath() + "," + violation.getMessage());
  }
  System.out.println("");
 }

 public static void main(String args[]) {

  Employee emp1 = new Employee(1, "Krishna", 1234567890);
  System.out.println("Validation errors on bean emp1");
  validateBean(emp1);

  Employee emp2 = new Employee(2, "Siva", 23456789.23);
  System.out.println("Validation errors on bean emp2");
  validateBean(emp2);
 }
}


Output
Validation errors on bean emp1
************************************
salary,numeric value out of bounds (<9 digits>.<2 digits> expected)

Validation errors on bean emp2
************************************
No validation errors....




Previous                                                 Next                                                 Home