Java: Arrays

Last updated on:

Processing Arrays:

1. Initializing arrays with input values:

java.util.Scanner input = new java.util.Scanner(System.in);
System.out.println("Enter" + myList.length + " values");
for(int i=0; i < myList.length.length; i++)
myList[i] = input.nextDouble();

2. Initializing arrays with random values:

for(int i=0; i < myList.length; i++){
myList[i] = Math.random()*100;
}

3. Displaying arrays:

for(int i = 0; i < myList.length; i++){
System.out.print(myList[i] + " ");
}

4. Summing all elements:

double total = 0;
for(int i=0; i < myList.length; i++){
total += myList[i];
}

5. Finding the largest element

double max = myList[0];
for(int i = 1; i < myList.length; i++){
if(myList[i] > max) max = myList[i];
}

6. Finding the smallest index of the largest element:

double max = myList[0];
int indexOfMax = 0;
for (int i = 1; i < myList.length; i++){
if(myList[i];
indexOfMax = i;
}

7. Random shuffling:

for (int i = myList.length - 1; i > 0; i--) {
// Generate an index j randomly with 0 <= j <= i
int j = (int)(Math.random()*(i + 1));

// Swap myList[i] with myList[j]
double temp = myList[i];
myList[i] = myList[j];
myList[j] = temp;
}

8. Shifting elements:

double temp = myList[0]; //Retain the first element

// Shift elements left
for(int i = 1; i < myList.length; i++) {
myList[i - 1] = myList[i];
}

// Move the first element to fill in the last position 
myList[myList.length - 1] = temp;

9. Simplifying coding

String[] months = {"January", "February", ... , "December"};
System.out.print("Enter a month number (1 to 12): ");
int monthNumber = input.nextInt();
System.out.println("The month is " + months[monthNumber - 1]);

If you dont use the months array, you would have to determine the month name using a length multi-way if-else statement as follows:

if (monthNumber == 1)
System.out.println("The month is January");
else if (monthNumber == 2)
System.out.println("The month is February");
...
else
System.out.println("The month is December");
View Comments

Leave a Comment

Use markdown or basic HTML and be nice.