Java Reference
In-Depth Information
heightArray[1] = 1.80f;
heightArray[2] = 1.90f;
heightArray[3] = 1.84f;
heightArray[4] = 1.88f;
//compute the BMIs and store in the BMIArray
BMIArray[0] = weightArray[0]/(heightArray[0]*heightArray[0]);
BMIArray[1] = weightArray[1]/(heightArray[1]*heightArray[1]);
BMIArray[2] = weightArray[2]/(heightArray[2]*heightArray[2]);
BMIArray[3] = weightArray[3]/(heightArray[3]*heightArray[3]);
BMIArray[4] = weightArray[4]/(heightArray[4]*heightArray[4]);
// print the BMIs to the screen
System.out.println("The BMI of person 1 is: " + BMIArray[0] + ".");
System.out.println("The BMI of person 2 is: " + BMIArray[1] + ".");
System.out.println("The BMI of person 3 is: " + BMIArray[2] + ".");
System.out.println("The BMI of person 4 is: " + BMIArray[3] + ".");
System.out.println("The BMI of person 5 is: " + BMIArray[4] + ".");
}
}
The output of the Java program is:
The BMI of person 1 is: 28.075043.
The BMI of person 2 is: 22.222223.
The BMI of person 3 is: 18.836565.
The BMI of person 4 is: 27.76465.
The BMI of person 5 is: 22.06881.
Multidimensional arrays are arrays where the elements are arrays themselves. A popular example of
this is a matrix. Consider the following Java class:
public class MatrixExample {
// declare and initialize the matrix
// This is our main method.
public static void main(String[] args){
int[][] matrix={{1, 2, 4},{2, 6, 8},{10, 20, 30}};
// print some of the matrix numbers to the screen
System.out.println("Element at row 0 and column 1 is: " + matrix[0][1] + ".");
System.out.println("Element at row 2 and column 2 is: " + matrix[2][2] + ".");
System.out.println("Element at row 2 and column 1 is: " + matrix[2][1] + ".");
System.out.println("Element at row 1 and column 0 is: " + matrix[1][0] + ".");
}
}
The matrix variable is an array of an array of integer numbers. It is immediately initialized during
declaration. The output of this program will be as follows:
Element at row 0 and column 1 is: 2.
Element at row 2 and column 2 is: 30.
Search WWH ::




Custom Search