Skip to content
Advertisement

The numbers never occur next to each other

I wrote a program that reads an array of integers and two numbers n and m. The program check that n and m never occur next to each other (in any order) in the array.

import java.util.*;
class Main {
    public static void main(String[] args) {
        // put your code here
        Scanner scanner = new Scanner (System.in);

        int len = scanner.nextInt();
        int [] array = new int [len];

        boolean broken = false;

        for (int i = 0; i < len; i++){
            array [i] = scanner.nextInt();
        }

        int n = scanner.nextInt();
        int m = scanner.nextInt();

        for (int j = 1; j < len; j++){
           if((array[j]==n)&&(array[j+1]==m) || (array[j]==n)&&(array[j-1]==m) || (array[j]==m)&&(array[j+1]==n) || (array[j]==m)&&(array[j-1]==n)){
                broken = true;
                break;

            }
        }
        System.out.println(broken);
    }
}

Test input:

3
1 2 3
3 4

Correct output: true

My output is blank. What am I doing wrong?

Advertisement

Answer

Your code will throw ArrayIndexOutOfBoundsException as you are using array[j+1] whereas you have loop condition as j < len. The condition should be j < len -1.

The following works as expected:

for (int j = 1; j < len - 1; j++) {
    if ((array[j] == n && array[j + 1] == m) || (array[j] == n && array[j - 1] == m)
            || (array[j] == m && array[j + 1] == n) || (array[j] == m && array[j - 1] == n)) {
        broken = true;
        break;

    }
}

A sample run:

3
1 2 3
3 4
true
Advertisement