Please answer all the following question in java language. 1. Declare and create
ID: 3695471 • Letter: P
Question
Please answer all the following question in java language.
1. Declare and create an int array with name: myArray and 15 elements.
2. Declare and initialize a two-dimension (4*3) String array with name my2DArray.
3.Given a two-dimension integer array: my2Darray, display all element values. You should complete it twice: one to use regular for statement and the other to use enhanced for statement.
4.Create a function using Variable-length Argument. Parameters’ type is int, and thisfunction will print out the sum of all element values on the screen.
Explanation / Answer
Ans;
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static int sum( int... numbers ){
int total = 0; // initialize total
for (int d : numbers ){
total += d;
}
return total;
}
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
int myArray[] = new int[15];
String my2DArray[][] = new String[4][3];
int my2Darray[][] = new int[4][3];
Random ran = new Random();
for(int i=0;i<15;i++){
myArray[i] = ran.nextInt(100);
}
for(int i=0;i<4;i++){
for(int j=0;j<3;j++){
my2Darray[i][j] = ran.nextInt(100);
}
}
System.out.println("Enter Strings:");
Scanner sc = new Scanner(System.in);
for(int i=0;i<4;i++){
for(int j=0;j<3;j++){
my2DArray[i][j] = sc.next();
}
System.out.println();
}
System.out.println("Regular");
for(int i=0;i<4;i++){
for(int j=0;j<3;j++){
System.out.print(" " +my2Darray[i][j]);
}
System.out.println();
}
System.out.println("Enhanced");
for(int []arr : my2Darray){
for(int a: arr){
System.out.print(" " +a);
}
System.out.println();
}
System.out.println( "Sum = "+sum(myArray) );
}
}