Академический Документы
Профессиональный Документы
Культура Документы
4. Multidimensional Arrays
public class MainClass {
public static void main(String args[]) {
double m[][] = {
{ 0*0, 1*0, 2*0, 3*0 },
{ 0*1, 1*1, 2*1, 3*1 },
{ 0*2, 1*2, 2*2, 3*2 },
{ 0*3, 1*3, 2*3, 3*3 }
};
int i, j;
for(i=0; i<4; i++) {
for(j=0; j<4; j++)
System.out.print(m[i][j] + " ");
System.out.println();
}
}
}
9. 4. 2. Arrays of Arrays
public class MainClass public class MainClass {
public static void main(String[] args) {
float[][] t = new float[10][365]; // Temperature array
for (int i = 0; i < t.length; i++) {
for (int j = 0; j < t[i].length; j++) {
t[i][j] = (float) (45.0 * Math.random() - 10.0);
}
}
float average = 0.0f;
for (int i = 0; i < t.length; i++) {
for (int j = 0; j < t[i].length; j++) {
average += t[i][j];
}
}
System.out.println(average);
}
}
44505.707
public static void main(String[] arg) {
float[][] samples = new float[6][]; // Define 6 elements,
// each is an array
for (int i = 0; i < samples.length; i++) {
samples[i] = new float[i + 1]; // Allocate each array
}
for (int i = 0; i < samples.length; i++) {
System.out.println(samples[i].length);
}
}
1
2
3
4
5
6
public static void main(String[] arg) {
long[][][] beans = new long[5][10][30];
for (int i = 0; i < beans.length; i++) {
for (int j = 0; j < beans[i].length; j++) {
beans[i][j] = new long[(int) (1.0 + 6.0 * Math.random())];
}
}
}
public class ArrayOfArraysDemo2 {
public static void main(String[] args) {
int[][] aMatrix = new int[4][];
// populate matrix
for (int i = 0; i < aMatrix.length; i++) {
aMatrix[i] = new int[5]; // create sub-array
for (int j = 0; j < aMatrix[i].length; j++) {
aMatrix[i][j] = i + j;
}
}
// print matrix
for (int i = 0; i < aMatrix.length; i++) {
for (int j = 0; j < aMatrix[i].length; j++) {
System.out.print(aMatrix[i][j] + " ");
}
System.out.println();
}
}
}
public static int getDimension(Object array) {
int dim = 0;
Class c = array.getClass();
while (c.isArray()) {
c = c.getComponentType();
dim++;
}
return (dim);
}
}
//2
public class ArrayOfArraysDemo {
public static void main(String[] args) {
String[][] cartoons = {
{ "Flintstones", "Fred", "Wilma", "Pebbles", "Dino" },
{ "Rubbles", "Barney", "Betty", "Bam Bam" },
{ "Jetsons", "George", "Jane", "Elroy", "Judy", "Rosie", "Astro" },
{ "Scooby Doo Gang", "Scooby Doo", "Shaggy", "Velma", "Fred", "Daphne" } };
for (int i = 0; i < cartoons.length; i++) {
System.out.print(cartoons[i][0] + ": ");
for (int j = 1; j < cartoons[i].length; j++) {
System.out.print(cartoons[i][j] + " ");
}
System.out.println();
}
}
}