﻿ Java exercises: Count the two elements of two given arrays of integers with same length, differ by 1 or less - w3resource # Java Exercises: Count the two elements of two given arrays of integers with same length, differ by 1 or less

## Java Basic: Exercise-100 with Solution

Write a Java program to count the two elements of two given arrays of integers with same length, differ by 1 or less.

Pictorial Presentation: Sample Solution:

Java Code:

``````import java.util.*;
import java.io.*;
public class Exercise100 {
public static void main(String[] args)
{
int[] array_nums1 = {10, 11, 10, 20, 43, 20, 50};
int[] array_nums2 = {10, 13, 11, 20, 44, 30, 50};
System.out.println("Array1: "+Arrays.toString(array_nums1));
System.out.println("Array2: "+Arrays.toString(array_nums2));
int ctr = 0;

for(int i = 0; i < array_nums1.length; i++) {
if(Math.abs(array_nums1[i] - array_nums2[i]) <= 1 && array_nums1[i] != array_nums2[i])
ctr++;
}

System.out.printf("Number of elements: "+ctr);
System.out.printf("\n");
}
}
```
```

Sample Output:

```Array1: [10, 11, 10, 20, 43, 20, 50]
Array2: [10, 13, 11, 20, 44, 30, 50]
Number of elements: 2
```

Flowchart: Java Code Editor:

What is the difficulty level of this exercise?

﻿

## Java: Tips of the Day

Execution of console commands:

Java allows you to execute console commands directly from code using a class Runtime. It is very important not to forget about exception handling.

For example, let's try to open a PDF file through a Java terminal:

```import java.io.BufferedReader;
import java.io.InputStream;

public class ShellCommandExec {

public static void main(String[] args) {
String gnomeOpenCommand = "gnome-open //home//user//Documents//MyDoc.pdf";

try {
Runtime rt = Runtime.getRuntime();
Process processObj = rt.exec(gnomeOpenCommand);

InputStream stdin = processObj.getErrorStream();

String myoutput = "";