Java multidimensional arrays

Write a method that creates and initializes a two-dimensional array of primitive type double. The size of the array is determined by the arguments of the method, and the initialization values are a range determined by beginning and ending values that are also arguments of the method (so four arguments total). Create a second method that will print the array generated by the first method. In main(), test the methods by creating and printing several different sizes of arrays. – asked by Raj on our Facebook profile

package com.itcuties.questions;

public class Answer {

	public double[][] createArray(int xSize, int ySize, double start, double end) {
		double[][] array = new double[xSize][ySize];
		
		// init values shouldn't be less than the value of start method argument
		double initValue = start;
		// init value step
		double step = (end - start)/10; // Let's say :)
		for (int x=0; x < xSize; x++) {
			for (int y=0; y < ySize; y++) {
				if (initValue <= end) {	
					array[x][y] = initValue;
				} else {
					initValue = start;
					array[x][y] = initValue;
				}
				initValue += step;
			}
		}
		return array;
	}
	
	public void printArray(double[][] array) {
		for (int x=0;x < array.length; x++) 
			for (int y=0;y < array[x].length; y++)
				System.out.println(array[x][y]);
	}
	
	public static void main(String[] args) {
		Answer a = new Answer();
		System.out.println("a.printArray(a.createArray(5, 5, 100, 102))");
		a.printArray(a.createArray(5, 5, 100, 102));
		System.out.println("a.printArray(a.createArray(15, 35, 100, 120))");
		a.printArray(a.createArray(15, 35, 100, 120));
		System.out.println("a.printArray(a.createArray(20, 12, 1, 10))");
		a.printArray(a.createArray(20, 12, 1, 10));
		System.out.println("a.printArray(a.createArray(2, 7, 65, 90))");
		a.printArray(a.createArray(2, 7, 65, 90));
		System.out.println("a.printArray(a.createArray(8, 20, 100, 200))");
		a.printArray(a.createArray(8, 20, 100, 200));
	}
}

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>