Advertisement
CoineTre

JF-LabArrays06.EqualArrays

Jan 18th, 2021
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.72 KB | None | 0 0
  1. package fundamentals.arrays;
  2. import java.util.Arrays;
  3. import java.util.Scanner;
  4.  
  5. public class Lab6EqualArrays {
  6.     public static void main(String[] args) {
  7.         Scanner scanner = new Scanner (System.in);
  8.         int[] firstArray = parseArr(scanner);
  9.         int[] secondArray = parseArr(scanner);
  10.         boolean equals = Arrays.equals(firstArray,secondArray);
  11.         int otherIndex = -1;
  12.         for (int i = 0; i < firstArray.length; i++) {
  13.             if (firstArray[i]!=secondArray[i]){
  14.                 otherIndex = i;
  15.                 break;
  16.         }
  17.         }
  18.         if (equals){
  19.             int sum = 0;
  20.             for (int i : firstArray) {
  21.                 sum+=i;
  22.             }
  23.             System.out.printf("Arrays are identical. Sum: %d%n",sum);
  24.         }else{
  25.             System.out.printf("Arrays are not identical. Found difference at %d index.", otherIndex);
  26.         }
  27.     }
  28.  
  29.     private static int[] parseArr(Scanner scanner) {
  30.         String firstInput = scanner.nextLine();
  31.         String[] firstNumbers = firstInput.split(" ");
  32.         int[] firstArray = new int[firstNumbers.length];
  33.         for (int i = 0; i < firstArray.length; i++) {
  34.             firstArray[i] = Integer.parseInt(firstNumbers[i]);
  35.         }
  36.         return firstArray;
  37.     }
  38. }
  39.  
  40. /*
  41. * Read two arrays and print on the console whether they are identical or not.
  42. *  Arrays are identical if their elements are equal. If the arrays are identical
  43. * find the sum of the first one and print on the console following message: "Arrays are identical. Sum: {sum}",
  44. * otherwise find the first index where the arrays differ and print on the console
  45. * following message: "Arrays are not identical. Found difference at {index} index."*/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement