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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.