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.

3
  • 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. Commented Jun 30, 2021 at 17:27
  • if your string has only digits, it's certainly a positive integer Commented Jun 30, 2021 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! Commented Jun 30, 2021 at 17:31

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.