For an assignment to study up on an incoming exam, I have to make these little functions. These are review style functions that make sure we know the algorithms and code necessary to do well on the test. I'm looking for anything I can improve upon in my code, so I can get the best grade possible.
- Write a method called evens that will receive a 2-D array of integers and return the sum of all the even integers in the array.
public int evens(int[][] arr) { int sum = 0; for(int[] row : arr) { for(int item : row) { if(item % 2 == 0) { sum += item; } } } return sum; }
- Write a method called check that will receive a 2-D array of String and a single letter (character). The method will return true if any of the strings start with the letter that is passed in (ignoring cases)
public boolean check(String[][] arr, char c) { for(String[] row : arr) { for(String item : row) { if(item.charAt(0) == c) { return true; } } } return false; }
- Write a method called getColumn which receives a 2-D array of doubles, and an integer parameter n. The method returns a one-dimensional array which contains the elements in the nth column of the 2-D array.
public double[] getColumn(double[][] arr, int col) { // row by column double[] newarr = new double[arr.length]; for(int i = 0; i < arr.length; i++) { newarr[i] = arr[i][col]; } return newarr; }
- Write a method called populate that takes two parameters, m and n. The method creates and returns an m x n matrix filled with the counting numbers in row-major order starting with one.
public int[][] populate(int m, int n) { int[][] arr = new int[m][n]; int count = 1; for(int i = 0; i < arr.length; i++) { for(int j = 0; j < arr[i].length; j++) { arr[i][j] = count; count++; } } return arr; }
My tester class (test.java)
import java.util.Arrays; public class test { public static void main(String[] args) { test t = new test(); int[][] array = { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10} }; String[][] array2 = { {"abc", "def", "ghi"}, {"jkl", "lmn", "opq"}, {"rst", "uvw", "xyz"} }; double[][] array3 = { {1.1, 1.2, 1.3, 1.4, 1.5}, {1.6, 1.7, 1.8, 1.9, 2.0}, {2.1, 2.2, 2.3, 2.4, 2.5}, {2.6, 2.7, 2.8, 2.9, 3.0} }; System.out.println("30 => " + t.evens(array)); System.out.println(); System.out.println("true => " + t.check(array2, 'd')); System.out.println(); System.out.println("[1.1, 1.6, 2.1, 2.6] => " + Arrays.toString(t.getColumn(array3, 0))); System.out.println(); System.out.println(Arrays.deepToString(t.populate(2, 5))); } }