mercredi 16 septembre 2020

Checking if an array contains two numbers

i have just started with Java and facing a problem right now, which i cannot solve after 2hrs of checking code. When i input : 7 ( as length) 6 3 4 8 3 2 6 (as array) 8 3 (as numbers to check)

it Writes false, but clearly they are included in the exact order. Please help me trying to understand what the problem is

here is the Code:


import java.util.Scanner;

public class checker {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int length = scanner.nextInt();
        int[] numbers = new int[length];

        boolean broken = false;
        for (int i = 0; i < numbers.length; i++) {
            numbers[i] = scanner.nextInt();
        }
        int n = scanner.nextInt();
        int m = scanner.nextInt();

        for (int j = 1; j < length; j++) {

            if (numbers[j] == n && numbers[j-1] == m || numbers[j] == m && numbers[j+1] == n || numbers[j] == m && numbers[j-1] == n || numbers[j] == n && numbers[j+1] == m) {
                broken = false;
            } else {
                broken = true;
            }

        }
        if (broken) {
            System.out.println("false");
        } else {
            System.out.println("true");
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire