List all Odd And Even Pairs in a string
List all Odd And Even Pairs in a string
The input is a string with integer values, for example, "1 2 3 4 5 6".
Your task is to check if pair is different, odd or even.
You can use the following test cases to verify your code logics.
ID | Input | Ouput |
---|---|---|
1 | 1 2 | different |
2 | 2 2 | Even |
3 1 2 3 3 6 6 1, 2 --> different 3, 3 --> both are odd 6, 6 --> both are even | ||
4 | "1 2 3 4 6" | Invalid length (since the count is a even number, 5) (the array of input numbers is not even!) |
Cut and paste the following code snippet to start solve this problem.
public class Main { public static void main(String[] args) { test("1 2"); test("2 2"); test("1 2 3 3 6 6"); test("1 2 3 4 6"); } public static void test(String inputStr) { //your code } }
Here is the answer to the question above.
public class Main { public static void main(String[] args) { test("1 2");/*from w w w . ja va 2 s .c o m*/ test("2 2"); test("1 2 3 3 6 6"); test("1 2 3 4 6"); } public static void test(String inputStr) { String[] inputStrArr = inputStr.split(" "); int countNumbers = inputStrArr.length; if ((countNumbers % 2) == 0) { for (int i = 0; i < countNumbers - 1; i = i + 2) { int number1 = Integer.parseInt(inputStrArr[i]); int number2 = Integer.parseInt(inputStrArr[i + 1]); if (((number1 % 2) == 0) && ((number2 % 2) == 0)) { // both are even System.out.printf("%d, %d --> both are even\n", number1, number2); } else if (((number1 % 2) != 0) && ((number2 % 2) != 0)) { // both are odd System.out.printf("%d, %d --> both are odd\n", number1, number2); } else { System.out.printf("%d, %d --> different\n", number1, number2); } } } else { System.out.println("Invalid length"); } } }