0

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.

2
  • Can you edit your post to ask a specific question? It's a good idea to share what you've tried so far, and explain why that doesn't work. Commented Sep 25, 2021 at 15:43
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. Commented Oct 3, 2021 at 8:40

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.