Friday, February 12, 2016

String[] array = {"This", "is", "an", "array"}

Arrays and matrices are essential in Java programming, and programming in general. they are groups of variables or objects that hold different data in them.
a single array holds as many variables of the same data requirements that you need.

int[] array = new int[7];
int x = 1;
for(int i : array){
 i = x;
x++;
}
//this program will create an array of integers

There are different ways to instantiating an array
String[] names = {"Edward", "Joseph", "Smigla"};
for(String name : names){
System.out.print(name + " ");
}
//this code will print: Edward Joseph Smigla on the console
//you can also pull any variable from an array using the index
names[1] = "E.";
names[1] = "J.";
names[1] = "Shmigs";
for(String name : names){
System.out.print(name + " ");
}//this code will print: E .J. Shmigs on the console
//the index of the arrays is in programmer numbers 0 - 2 for arrays with 3 indexes
//always decreasing the index number by one from the amount of indexes

you can also create arrays of objects such as this:
public Integer[] array = new Integer[32];
for(int i = 0; i < array.length(); i++){
array[i] = (int)(Math.random()*32);
}//Remember to cast because Math.random() give a double //variable
// you do not need to use the for-each loop to cycle through arrays, you can also use the length()
//method, which finds the length of the array given  and returns it

You can also create arrays of arrays which are called matrices or 2D arrays (you can create as many arrays of arrays as needed)

int[][] numbers = new int[5][5];//this will create a 2D array containing 25 int variables
for(int i = 0; i < array.length(); i++){
for(int j = 0; j < array[i].length(); j++){
array[i][j] = (int)(Math.random() * 25);
System.out.print(array[i][j] + " ");
}
System.out.println();
}//to give values to multiple index arrays you need multiple loops
//this will print random values from 0 - 24, 25 times (with a space in between and a new line every //five variables)

Matrices can be instantiated in different ways like the simple array.

int[][] numbers = {{1,2,3},{4,5,6},{7,8,9}};
//this instantiates a 2D array with the variables 1,2,3,4,5,6,7,8, and 9. in different levels of the array

No comments:

Post a Comment