0

I'm attempting to test user input for a function without using the try/catch method. I need to test the String input to be both > 0 and also test that it is an integer. Is there any advice on how to implement this?

Thank you.

Jack M
  • 1
  • Once you've checked if it's an integer, checking if it's greater than zero is trivial. [Checking whether it's an integer is a solved problem.](https://stackoverflow.com/questions/237159/whats-the-best-way-to-check-if-a-string-represents-an-integer-in-java) – Green Cloak Guy Jun 30 '21 at 17:27
  • if your string has only digits, it's certainly a positive integer – shikida Jun 30 '21 at 17:29
  • Right, but how would i go about checking this? I currently take the input as a String, and then convert using parseInt. But how would i go about checking the string for an integer prior to converting? Obviously the function would fall apart during the conversion if a non-integer was inputted. Thanks! – Jack M Jun 30 '21 at 17:31

1 Answers1

1

Use this to check

import java.util.regex.Pattern;

public class NaturalNumberChecker {

public static final Pattern PATTERN = Pattern.compile("[0-9]+");

   boolean isNaturalNumber(String input) {
    return input != null && PATTERN.matcher(input).matches();
  }
}

if wants to handle the case when user may enter integer with spaces use trim method to delete leading and trailing spaces in user input

anish sharma
  • 568
  • 3
  • 5