简体   繁体   中英

Iterating over arrays Check if an array contains two numbers

Write a program that reads an unsorted array of integers and two numbers n and m . The program must check if n and m occur next to each other in the array (in any order).

Input data format

  • The first line contains the size of an array.
  • The second line contains elements of the array.
  • The third line contains two integer numbers n and m .

All numbers in the same line are separated by the space character.

Output data format

Only a single value: true or false .

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int size = scanner.nextInt();
        int[] table = new int[size];
        for (int i = 0; i < table.length; i++) {
            table[i]=scanner.nextInt();
        }
        int n = scanner.nextInt();
        int m = scanner.nextInt();

        for (int i = 0; i < table.length ; i++) {
            //stuck here 
        }
    }
}

I think it can help you:

        for (int i = 0; i < table.length-1 ; i++) {
            if (table[i] == m){
                if (table[i+1] == n) {
                    System.out.println("true");
                    return;
                }
            }
            if (table[i] == n){
                if (table[i+1] == m) {
                    System.out.println("true");
                    return;
                }
            }
        }
        System.out.println("false");

This will pass all tests:

import java.util.Scanner;

class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

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

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

        int n = scanner.nextInt();
        int m = scanner.nextInt();
        boolean valuesAreNotOccurNearEachOther = true;

        for (int i = 0; i < array.length - 1; i++) {
            if (array[i] == n || array[i] == m) {
                if (array[i + 1] == m) {
                    valuesAreNotOccurNearEachOther = false;
                }
                if (array[i + 1] == n) {
                    valuesAreNotOccurNearEachOther = false;
                }
            }
        }

        System.out.println(valuesAreNotOccurNearEachOther);
    }
}

Honest question, I am working on the question and trying a more concise solution. Why doesn't this block of code work? It keeps printing true if the test is

3

1 2 3

3 2

            if ((table[i+1] == m)  || (table[i-1] == m)) {
                System.out.println("false");
                return;
                
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM