Skip to the content.

Arrays

AP CSA

ArrayList<String> al = new ArrayList<String>();

al.add("Apple");
al.add("Orange");
al.add("Banana");

System.out.print(al);
System.out.println();

for (int i = 0; i < al.size() - 1; i++) {
    for (int j = 0; j < al.size() - i - 1; j++) {
        if (al.get(j).charAt(0) > al.get(j + 1).charAt(0)) {
            String temp = al.get(j);
            al.set(j, al.get(j + 1));
            al.set(j + 1, temp);
        }
    }
}

for (String fruit : al) {
    System.out.println(fruit);
}
[Apple, Orange, Banana]
Apple
Banana
Orange

Homework


Write a program that randomly fills in 0s and 1s into an n-by-n matrix, prints the matrix, and finds the rows and columns with the most 1s. (Hint: Use two ArrayLists to store the row and column indices with the most 1s.)

import java.math.*;


int[] getRanNum(int reps) {
    Random rand = new Random();
    int[] result = new int[reps];
    
    for (int rep = 0; rep < reps; rep++) {
        double num = rand.nextDouble();
        if (num > 0.5) {
            result[rep] = 1;
        } else {
            result[rep] = 0;
        }
    }

    return result;
}


int times = 4;
int[][] array = new int[times][times];

for (int time = 0; time < times; time++) {
    int[] index = getRanNum(times);
    array[time] = index;
    System.out.println(Arrays.toString(array[time]));
}

int rows = array.length;
int cols = array[0].length;

int maxOnes = 0;
int rowWithOnes = 0;
for (int row = 0; row < rows; row++)
{
    int onesCount = 0;
    for (int col = 0; col < cols; col++)
    {
        if (array[row][col] == 1) {
            onesCount++;
        }
    }
    if (onesCount > maxOnes) {
        maxOnes = onesCount;
        rowWithOnes = row;
    }
}

System.out.println("Row with the most 1's: Row " + rowWithOnes + " with " + maxOnes + " ones.");

[1, 0, 1, 1]
[1, 1, 0, 1]
[1, 0, 1, 0]
[0, 0, 0, 1]
Row with the most 1's: Row 0 with 3 ones.