Check if String contain only 2 numbers separated by 1 comma in Java

Viewed 2476

I need to validate the lines of an input. But each line can only contain 2 numbers separated by 1 comma. Example of format:

1,4

2,7

8,9

Also the first number must be under a certain max (my program checks the max value possible by a id.size() method, it gives the size of a list and that must be the maximum number possible for the first number of the string).

Second number can be any value.

4 Answers

You can use regular expressions to validate that you have two numbers separated by a comma, if you are only working with integers.

if(str.matches("-?[0-9]+,-?[0-9]+")){
 //valid
} else {
 //invalid
}

After that, you can use String#split along with Integer.parseInt to get the two numbers.

final String[] parts = str.split(",");
final int num1 = Integer.parseInt(parts[0]);
final int num2 = Integer.parseInt(parts[1]);
if(num1 < MAX_VALUE_FOR_FIRST_NUM){
   //valid
} else {
  //invalid; display error message
}

Use this for getting both numbers (s is input string):

int first=Integer.parseInt(s.split(",")[0].trim().replace("(", ""));
int second=Integer.parseInt(s.split(",")[1].trim().replace(")", ""));

This will get you number and get rid of ( and ). You should use this for each line that you enter. For checking did input has more numbers use this:

if(s.split(",").length>2){
    //show some error
}

After this you only need to check numbers for min and max value for them.

First of all, you want to check if the line you have contains 2 numbers and one comma, and then you have to check if the two substrings that the comma makes are digits. So the code you want is the following.

public static void main(String[] args) throws IOException {

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter String: ");
    String line = br.readLine();
    System.out.println(line);

    int max_number = 100;
    int firstNumber = 0, secondNumber = 0;
    if (line.contains(",")) {
        if(isNumeric(line.substring(0,line.indexOf(","))) && isNumeric(line.substring(line.indexOf(",")+1))){
            firstNumber = Integer.parseInt(line.substring(0,line.indexOf(",")));
            secondNumber = Integer.parseInt(line.substring(line.indexOf(",")+1));
        }

    }

    if(firstNumber <= max_number){
        System.out.println("FirstNumber: " + firstNumber + " SecondNumber: " + secondNumber);
    }

}

public static boolean isNumeric(String str) {
    if (str == null) {
        return false;
    }
    try {
        double d = Double.parseDouble(str);
    } catch (NumberFormatException nfe) {
        return false;
    }
    return true;
}

You can extract the two numbers using Regular Expression and then check the max condition for the number.

String regex = "^(-?\\d+),(-?\\d+)$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input); // input as 1,4

if (matcher.find()) {
    int num1 = matcher.group(1));
    int num2 = matcher.group(2));
    
    if (num1 == id.size()) {
        // some logic
    }
    
    // some more logic
}
Related