[Løst] Odd and Even Pairs - Java Task

  

3
Emne starter

You are given an array of integers as a single line, separated by a space. Write a program that checks consecutive pairs and prints if both are odd/even or not. Note that the array length should also be an even number:

even and odd pairs in Java

1 Answer
2

Here is my solution, dude:

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
 
public class Pr_08_OddAndEvenPairs {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
 
        String[] input = scanner.nextLine().split(" ");
 
        List<Integer> numbers = new ArrayList<>();
        for (int i = 0; i < input.length; i++) {
            numbers.add(Integer.parseInt(input[i]));
        }
 
        if (numbers.size() % 2 != 0) {
            System.out.println("Invalid length");
        }
 
        for (int i = 0; i < numbers.size(); i += 2) {
            if (numbers.get(i) % 2 == 0 && numbers.get(i + 1) % 2 == 0) {
                System.out.printf("%1$d, %2$d -> both are even", numbers.get(i), numbers.get(i + 1));
                System.out.println();
            } else if (numbers.get(i) % 2 != 0 && numbers.get(i + 1) % 2 != 0) {
                System.out.printf("%1$d, %2$d -> both are odd", numbers.get(i), numbers.get(i + 1));
                System.out.println();
            } else {
                System.out.printf("%1$d, %2$d -> different", numbers.get(i), numbers.get(i + 1));
                System.out.println();
            }
        }
    }
}
Del: