Home > Enterprise >  create a two dimensional (2D) array in java
create a two dimensional (2D) array in java

Time:09-25

I am working on a java code that calculates the average of an array and it is working perfectly in serving its purpose but I want to modify it to be a 2D array (Two-dimensional).

import java.util.*;
public class Test3{
   public static void main(String [] args){
      Scanner adnan = new Scanner(System.in);
      System.out.println("Enter the length of the array : ");
      int length = adnan.nextInt();
      int [] input = new int [length];
      System.out.println("Enter Numbers : ");
      for ( int i = 0; i < length; i  ){
         input [i] = adnan.nextInt();
      }
      float average = average(input);
      System.out.println("Average of all numbers in the array : "   average);
      adnan.close();
   }
   public static float average(int [] input){
      float sum = 0f;
      for ( int number : input){
         sum = sum   number;
      }
      return sum / input.length;
   }
}

any help would be really appreciated because I am not too good at 2D arrays.

CodePudding user response:

In Java a 2D Array is declared using double brackets T [][]:

public static void main(String[] args) {

    // mock to not to use a stdin redirection or enter data manually
    ByteArrayInputStream system_in = new ByteArrayInputStream("3 2 5 8 1 6 7 2".getBytes(UTF_8));

    Scanner adnan = new Scanner(system_in);

    System.out.println("Enter rows number: ");
    final int rows = adnan.nextInt();

    System.out.println("Enter rows number: ");
    final int cols = adnan.nextInt();

    final int [][] input = new int[rows][cols];

    System.out.println("Enter Numbers : ");
    for (int row = 0; row < rows; row  ) {
        for (int col = 0; col < cols; col  ) {
            input[row][col] = adnan.nextInt();
        }
    }
    double average = average(input);
    System.out.println("Average of all numbers in the array : "   average);
    adnan.close();
}

public static double average(int[][] input) {
    // use streams or you can use the `Enter Numbers...` way
    return Arrays.stream(input)
            .flatMap(x -> Arrays.stream(x).boxed())
            .mapToInt(x -> x).average()
            .getAsDouble();
}

with output

Enter rows number: 
Enter rows number: 
Enter Numbers : 
Average of all numbers in the array : 4.833333333333333

CodePudding user response:

You can just reuse your method for calculating the average of a one dimensional array:

import java.util.Arrays;

class Main {
  public static void main(String[] args) {
    int[] arr = { 1, 2, 3, 4 };
    System.out.println(Arrays.toString(arr));
    System.out.printf("Average: %.2f%n", arrayAverage(arr));
    int[][] twoDimensionalArr = { { 1, 2 }, { 3, 4 }, { 5 } };
    System.out.println(Arrays.deepToString(twoDimensionalArr));
    System.out.printf("Average: %.2f%n", twoDimensionalArrayAverage(twoDimensionalArr));
  }

  public static double arrayAverage(int[] arr) {
    int n = arr.length;
    if (n == 0)
      return 0;
    double total = 0;
    for (int x : arr)
      total  = x;
    return total / n;
  }

  public static double twoDimensionalArrayAverage(int[][] twoDimensionalArr) {
    int m = twoDimensionalArr.length;
    if (m == 0)
      return 0;
    double total = 0;
    for (int[] arr : twoDimensionalArr)
      total  = arrayAverage(arr);
    return total / m;
  }
}

Output:

[1, 2, 3, 4]
Average: 2.50
[[1, 2], [3, 4], [5]]
Average: 3.33
  • Related