Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: Troubles with accessing data from outside the class.

  1. #1
    Junior Member
    Join Date
    Aug 2011
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Troubles with accessing data from outside the class.

    Hello all... I am currently working on a program that randomly generates a 19 x 10 Array2D with one "X" bot, and 9 numbered bots scattered about the map. I am then supposed to create a separate collection (I chose ArrayList) that stores all the numbered bots, calculates their distances from the X bot, and sorts the ArrayList from closest to furthest from the Xbot. Here is my code, as well as the problems I have had thus far in the code notes above the program.

     
    /*
    *   Number One:  Whenever I attempt to add the newly created "NumberBots" to my ArrayList (on line 70 specifically)
    *				it throws an out of bounds exception at me. I am totally unsure as to why this is happening!!
    *			    When I initialize the Collection list, it is of size 9, so I don't understand why it is saying it
    *			    is going out of bounds.  MAybe you can shed some light on the situation after looking at the code!
    *
    *   Number Two:  I have now organized everything into classes, so that the main is looking much better.  However, I am pretty confused as to
    *			   	how I can get the Xbot's location passed into my Collection class, so that I can execute the sorting algorithm and then print.
    *			   Specifically on lines 127 - 143.
    *
    *			   I have methods that allow the Xbot to retrieve it's own location once I have it created, but I am unsure where to go from here.
    *			   Hopefully you have a few guiding words that will help push me towards finishing this.  Thanks!!!
    */
     
    import java.util.Random;
    import java.util.*;
     
    class Array2DExampleAndrewBrooks1 {
    	public static void main(String args[]) {
     
    		Array2DCreation numbers = new Array2DCreation();
     
    		numbers.setBots();
    		numbers.print();
     
                    //sort the ArrayList
                    //print the ArrayList
     
    	}
    }
     
    class Array2DCreation {
    	private static final int MAX_X = 19;
    	private static final int MAX_Y = 10;
     
    	Random random = new Random();
    	int randomInt1 = random.nextInt(MAX_X);
    	int randomInt2 = random.nextInt(MAX_Y);
     
    	Array2D<Bot> numbers;
     
    	public Array2DCreation() {
    		numbers = new Array2D<Bot>(MAX_X, MAX_Y);
    		numbers.initialize(null);
    		numbers.start(0,0, Array2D.DOWN);
    	}
    	public void setBots() {
    		setXbot();
    		setNumberBots();
    	}
    	public void setXbot() {
    		Xbot bot1 = new Xbot();
    		bot1.setCoordinates(randomInt1, randomInt2);
    		numbers.set(randomInt1,randomInt2,bot1);
    	}
     
    	public void setNumberBots() {
     
    		Collection list = new Collection();
     
    		for(int k = 0; k < 9 ; k++) {
    			boolean isUnique = false;
     
    			while(isUnique == false) {
     
    				int randoX = random.nextInt(MAX_X);
    				int randoY = random.nextInt(MAX_Y);
     
    				if(numbers.get(randoX, randoY) == null) {
     
    					NumberBot bot = new NumberBot();
    					bot.setCoordinates(randoX, randoY);
    					bot.setCounter(bot.getCounter());
    					//list.add(bot.getCounter(), bot);     // THIS is the line of code that is throwing the out of bounds exception
    					numbers.set(randoX, randoY , bot);
    					isUnique = true;
     
    				} else {
     
    					randoX = random.nextInt(MAX_X);
    					randoY = random.nextInt(MAX_Y);
    				}
    			}
    		}
    	}
    	public void print() {
    		for(int i = 0; i < MAX_Y; i++) {
    			numbers.start(0, i, Array2D.RIGHT);
    				if(numbers.get() == null) {
    					System.out.print(" ");
    				} else {
    					System.out.print(numbers.get() + " ");
    				}
    				while (numbers.hasNext()) {
    					numbers.next();
    					if(numbers.get() == null) {
    						System.out.print(" ");
    					} else {
    						System.out.print(numbers.get() + " ");
    					}
    				}
    						System.out.println();
    		}
    	}
    }
    class Collection {
    	List<Bot> list;
     
    	public Collection() {
    		list = new ArrayList<Bot>(9);
    	}
     
    	public void add(int index, NumberBot bot) {
     
    		list.set(index, bot);
     
    	}
     
    	/*public static void sortList(List<Bot> list) { //This is my failed sort algorithm as I cannot figure out how to access xbot
     
    			Bot tempBot;
     
    			for(int k = 0; k < list.size(); k++) {
     
    				if (calculateDistance(bot, list.get(k)) > calculateDistance(bot, list.get(k+1))) {
     
    					tempBot = list.get(k);
    					list.set(k, list.get(k+1));
    					list.set((k+1), tempBot);
    				}
    			}
     
    			print(list);
     
    		}*/
     
    	public static void print(List<Bot> list) {
     
    		for(int i = 0; i < list.size(); i++ ) {
     
    			System.out.println("Numbered Bot " + (list.get(i)).toString());
    		}
    	}
     
    }
     
    abstract class Bot {
    	private int xCoordinate;
    	private int yCoordinate;
     
    	abstract public String toString();
     
    	public void setCoordinates(int xCoordinate, int yCoordinate) {
     
    		this.xCoordinate = xCoordinate;
    		this.yCoordinate = yCoordinate;
    	}
     
    	public int getX() {
    		return xCoordinate;
    	}
     
    	public int getY() {
    		return yCoordinate;
    	}
    	public double calculateDistance(Bot b) {
    		double totalDistance = 0;
    		int xDifference;
    		int yDifference;
     
    		if(xCoordinate > b.getX()) {
    			if(yCoordinate > b.getY()) {
    				xDifference = (xCoordinate - b.getX());
    				yDifference = (yCoordinate - b.getY());
    			} else {
    				xDifference = (xCoordinate - b.getX());
    				yDifference = (b.getY() - yCoordinate);
    			}
     
    		} else {
    			if(yCoordinate > b.getY()) {
    				xDifference = (b.getX() - xCoordinate);
    				yDifference = (yCoordinate - b.getY());
    			} else {
    				xDifference = (b.getX() - xCoordinate);
    				yDifference = (b.getY() - yCoordinate);
    			}
    		}
     
    		totalDistance = Math.sqrt(Math.pow(xDifference, 2) + Math.pow(yDifference, 2));
    			return totalDistance;
    	}
    }
     
    class Xbot extends Bot{
     
    	public String toString() {
    		return "X";
    	}
    }
     
    class NumberBot extends Bot{
    	private static int botCounter = 0;
    	private int botNumber;
     
    	public NumberBot() {
    		super();
    		botCounter = botCounter + 1;
    	}
     
    	public static int getCounter() {
    		return botCounter;
    	}
     
    	public void setCounter (int botCounter) {
    		botNumber = botCounter;
    	}
     
    	public String toString() {
    		return Integer.toString(botNumber);
    	}
    }

    The Array2D class:

    /**
     * Implements two dimensional arrray with generics and safe get and
     * set operations in other words it prevents array index out of bound
     * exception. Note that this class will cause compiler warnings but
     * that is acceptable. T is generic type specified when you create a
     * variable of type Array2D. For example to create two dimensional
     * of Double numbers called doubleArray2D you would declare it as:<b/>
     * Array2D<Double> doubleArray2D = new Array2D(20, 10);
     */
    public class Array2D<T> {
    	public static final int NONE  = 0;
    	public static final int UP    = 1;
    	public static final int RIGHT = 2;
    	public static final int DOWN  = 3;
    	public static final int LEFT  = 4;
    	int sizeX;
    	int sizeY;
    	T[][] elements;
    	int x;
    	int y;
    	int direction;
     
    	public Array2D(int sizeX, int sizeY) {
    		this.sizeX = sizeX;
    		this.sizeY = sizeY;
    		// We can't create an array of generics thus typecasting:
    		elements = (T[][])new Object[sizeX][sizeY];
    		this.x = 0;
    		this.y = 0;
    		this.direction = NONE;
    	}
    	/**
    	 * Gets element at row x and column y. If x and y are invalid row and
    	 * column then return null. The actual return type T will be the type
    	 * specified in between < and > when Array2D is declared. For example:
    	 * Array2D<Player> playerTiles;
    	 */
    	public T get(int x, int y) {
    		if (x>=0 && x<sizeX && y>=0 && y<sizeY) {
    			return elements[x][y];
    		} else {
    			return null;
    		}
     
    	}
    	/**
    	 * Sets element at row x and column y to a value of t. If x and y are
    	 * invalid row and column then nothing will be set. The actual type T
    	 * of t will be the type specified in between < and > when Array2D is
    	 * declared. For example:
    	 * Array2D<Player> playerTiles;
    	 */
    	public void set(int x, int y, T t) {
    		if (x>=0 && x<sizeX && y>=0 && y<sizeY) {
    			elements[x][y] = t;
    		}
    	}
    	/**
    	 * Sets row, and column of the first element to be read or written as
    	 * well as direction in which next element is read or written. Has to
    	 * be called before get(), set(T t), hasNext() and next() methods.
    	 */
    	public void start(int x, int y, int direction) {
    		this.x = x;
    		this.y = y;
    		this.direction = direction;
    	}
    	/**
    	 * Gets element at the position specified by start method. Should only
    	 * be called after start method is called to specify row, column and
    	 * direction.
    	 */
    	public T get() {
    		return get(x, y);
    	}
    	/**
    	 * Sets element at the position specified by start method. Should only
    	 * be called after start method is called to specify row, column and
    	 * direction.
    	 */
    	public void set(T t) {
    		set(x, y, t);
    	}
    	/**
    	 * Returns true is there is another element in direction specified by
    	 * by start method, otherwise returns false.
    	 */
    	public boolean hasNext() {
    		int tempX = x;
    		int tempY = y;
    		switch (direction) {
    			case UP:
    				tempY-=1;
    			break;
    			case DOWN:
    				tempY+=1;
    			break;
    			case LEFT:
    				tempX-=1;
    			break;
    			case RIGHT:
    				tempX+=1;
    			break;
    			default: // do nothing
    			break;
    		}
    		if (tempX>=0 && tempX<sizeX && tempY>=0 && tempY<sizeY) {
    			return true;
    		} else {
    			return false;
    		}
    	}
    	/**
    	 * Moves to next element in direction specified by start method so all
    	 * subsequent calls to get() and set(T t) will work on this next element.
    	 */
    	public void next() {
    		// Change x or y depending on the direction the array is read
    		switch (direction) {
    			case UP:
    				y-=1; // same as: y=y-1;
    			break;
    			case DOWN:
    				y+=1; // same as: y=y+1;
    			break;
    			case LEFT:
    				x-=1;
    			break;
    			case RIGHT:
    				x+=1;
    			break;
    			default: // do nothing
    			break;
    		}
    	}
    	/**
    	 * Initializes all elements of this 2D array to a specified value
    	 * of t.
    	 */
    	public void initialize(T t) {
    		for (int x=0; x<sizeX; x++) {
    			for (int y=0; y<sizeY; y++) {
    				elements[x][y] = t;
    			}
    		}
    	}
    }
    Last edited by broo7198; November 12th, 2011 at 01:26 AM. Reason: grammar


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Troubles with accessing data from outside the class.

    What specific questions do you have?
    Are you getting errors? Please copy and paste here the full text of the error messages.

Similar Threads

  1. accessing class method problem
    By steel55677 in forum Object Oriented Programming
    Replies: 11
    Last Post: February 23rd, 2012, 08:50 PM
  2. Adding data to a text box on another class
    By Qualitystreet in forum AWT / Java Swing
    Replies: 3
    Last Post: April 5th, 2011, 02:38 AM
  3. problem with data access when a class call another class
    By ea09530 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: April 4th, 2010, 05:20 PM
  4. Accessing a method of one class in another class
    By Sai in forum What's Wrong With My Code?
    Replies: 6
    Last Post: March 23rd, 2010, 04:06 PM
  5. [SOLVED] Problem accessing specific data in an array and getting it to return properly
    By Universalsoldja in forum Collections and Generics
    Replies: 3
    Last Post: February 4th, 2010, 04:26 PM