Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to set integer and string range from string in Java

The input given is Integer + String, however I want to set a range of integer input (1~34) and String (A~F).
if I do,

int i = (Integer.parseInt(input));

if (n > 34) {
    System.out.println("number too high");
}

it gives me

Exception in thread "main" java.lang.NumberFormatException: For input string: "35A"

is there any way to make this work? thanks in advace 🙁

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

if the string is 1A to 34F it should pass, anything over that should fail.. please help!

>Solution :

You could first split the String into number and letter

String[] split = n.split("(?=[A-Z])");

then check if the two parts fit your needs

if(Integer.parseInt(split[0]) > 34 || split[1].charAt(0) > 'F') {
    System.out.println("number too high");
}

You’d have to check beforehand that your String actually conforms to that pattern but you said in the comments that it’s always in that format, so it should work. Also if lowercase letters are possible you have to change the regex and condition or simply call toUppercase() on the input String.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading