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:

Java Basic Exercises: Count the two elements of two given arrays of integers with same length, differ by 1 or less.

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:

Flowchart: Java exercises: Count the two elements of two given arrays of integers with same length, differ by 1 or less.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to check if a specified number appears in every pair of adjacent element of a given array of integers.
Next: Write a Java program to check if the number of 10 is greater than number to 20's in a given array of integers.

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;
import java.io.InputStreamReader;
  
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();
      InputStreamReader isr = new InputStreamReader(stdin);
      BufferedReader br = new BufferedReader(isr);
  
      String myoutput = "";
  
      while ((myoutput=br.readLine()) != null) {
        myoutput = myoutput+"\n";
      }
      System.out.println(myoutput);
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
}