/** Lab 4 for CS 363 - calculate array address for any number of dimensions * Step 1 - Do array calculations based on row-major order. * Example input data: if the dimensions are (4,6,8,10) and we * want the (1,3,5,7) element, the base address is 100 and elements * have 4 bytes each, the answer should be 3208. (Hint: offset=777). * Step 2 - Do it also for column-major order. * Step 3 - Reject input where any of the array indices are not in the * proper bounds. For example, if the dimensions of the array are * 8 10, then 0 <= row <= 7 and 0 <= column <= 9. * Step 4 - THINK about, but you don't have to implement: * What would you change if the array indices begin at 1 instead of 0? */ import java.util.Scanner; import java.util.StringTokenizer; public class Driver { public static void main(String [] args) { // Get input from the user. Scanner in = new Scanner(System.in); System.out.printf("Enter the dimensions of the array. For example, " + "for int a[4][7] enter just the numbers 4 7\n" + "dimensions --> "); String dimensions = in.nextLine().trim(); System.out.printf("What is the array's base address? --> "); int base = Integer.parseInt(in.nextLine().trim()); System.out.print("How many bytes per entry? --> "); int size = Integer.parseInt(in.nextLine().trim()); System.out.println("Enter array reference you want the address for. " + "For example for a[1][5] enter just 1 5"); System.out.print("array reference --> "); String reference = in.nextLine().trim(); // Store dimensions and array reference coefficients. StringTokenizer tok = new StringTokenizer(dimensions, " "); int numDimensions = 0; while (tok.hasMoreTokens()) { ++ numDimensions; tok.nextToken(); } int [] dimension = new int[numDimensions]; tok = new StringTokenizer(dimensions, " "); int i = 0; while (tok.hasMoreTokens()) dimension[i++] = Integer.parseInt(tok.nextToken()); int [] index = new int[numDimensions]; tok = new StringTokenizer(reference, " "); for (i = 0; i < numDimensions; ++i) index[i] = Integer.parseInt(tok.nextToken()); //////////////////////////////////////////////////////////////////////// // At this point we have all our input for array address calculation! // Array dimension[] has all the dimensions of the array. // Array index[] has the indices of the array reference. // integer size has the number of bytes per entry. // integer base has the base address of the array. // ADD CODE HERE... //////////////////////////////////////////////////////////////////////// int addr = 0; System.out.printf("The address of your element is %d\n", addr); } }