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
andm
.
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 } } }
Advertisement
Answer
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");