<?xml version="1.0" encoding="ISO-8859-1"?>

<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/">
	<channel>
		<title>Java Programming Forum - Learn Java Programming - Blogs - sunde887</title>
		<link>http://www.java-forums.org/blogs/sunde887/</link>
		<description>Java Programming Forum - Learning Java easily</description>
		<language>en</language>
		<lastBuildDate>Fri, 24 May 2013 19:40:15 GMT</lastBuildDate>
		<generator>vBulletin</generator>
		<ttl>60</ttl>
		<image>
			<url>http://www.java-forums.org/images/misc/rss.jpg</url>
			<title>Java Programming Forum - Learn Java Programming - Blogs - sunde887</title>
			<link>http://www.java-forums.org/blogs/sunde887/</link>
		</image>
		<item>
			<title>Breakout Tutorial</title>
			<link>http://www.java-forums.org/blogs/sunde887/93-breakout-tutorial.html</link>
			<pubDate>Thu, 20 Oct 2011 22:32:12 GMT</pubDate>
			<description>The first step in designing something is to think it through. What pieces should it have and how should they work together? What methods, and...</description>
			<content:encoded><![CDATA[<blockquote class="blogcontent restore">The first step in designing something is to think it through. What pieces should it have and how should they work together? What methods, and instance variables should a class have? Let’s start by naming the classes we will need for brick breaker (or breakout/whatever you want to name it). <br />
<br />
We will need a paddle which the player controls, a ball which moves around the screen, and the bricks which are meant to be broken. There will also be a canvas class which everything is drawn upon. I plan to also provide some ideas for changes that I believe would be beneficial for you to try.<br />
Let’s start with the paddle, what should it do? The paddle seems simple, it simply moves along some horizontal line. This paddle will also be able to draw itself, and check if a ball hits it. The first thing the class needs however; is the ability to store its location on the screen. Since the paddle moves horizontally, the only changeable variable will be the x position. Here is the full code for the Paddle class, and below it is an explanation of the entire class:<br />
<div class="bbcode_container">
	<div class="bbcode_description">Java Code: </div>

	<pre class="brush: java">import java.awt.Color;
import java.awt.Graphics2D;

public class Paddle {
	public static final int Y_POS = Canvas.HEIGHT - 30;
	public static final int PADDLE_WIDTH = 80;
	public static final int PADDLE_HEIGHT = 10;
	public static final Color PADDLE_COLOR = Color.black;
	private int xPos;
	public static final int DELTA_X = 5;
	private int score;
	private int lives;
	
	public Paddle(int xPos){
		this.xPos = xPos;
		score = 0;
		lives = 5;
	}
	
	public void setX(int xPos){ 
		this.xPos = xPos;
		if(xPos &lt; 0) this.xPos = 0;
		if(xPos &gt; (Canvas.WIDTH - PADDLE_WIDTH)) this.xPos = (Canvas.WIDTH - PADDLE_WIDTH);
	}
	
	public int getX(){ return xPos; }
	public int getScore(){ return score; }
	public void setScore(int score){ this.score = score; }
	public int getLives(){ return lives; }
	public void setLives(int lives){ this.lives = lives; }
	
	/**
	 * Determines whether a Ball has hit the paddle
	 * 
	 * Checks if ball is in range of the paddles x's first. If
	 * it ball.x &gt; paddle.x but less than paddle.x + PADDLE_WIDTH + 15
	 * it is in the horizontal range. 
	 * 
	 * Next checks if it is actually hitting the paddle. if ball.y + the diameter
	 * is close to the paddles y position the method returns true. Has a final
	 * condition which gives somewhat of an error buffer to make sure the method
	 * doesn't allow the ball to skip over the threshhold and thus go right through
	 * the paddle
	 * 
	 * @param b
	 * @return
	 */
	public boolean hitPaddle(Ball b){
		if(b.getX() &lt;= xPos + (PADDLE_WIDTH + 15)){
			if(b.getX() &gt;= xPos - 10){
				if((b.getY() + (Ball.DIAMETER - 1)) &gt;= (Y_POS)){
					if((b.getY() + (Ball.DIAMETER - 1)) &lt;= (Y_POS + (PADDLE_HEIGHT - 5))){
						return true;
					}
				}
			}
		}
		return false;
	}
	
	public void drawPaddle(Graphics2D g){
		g.setColor(PADDLE_COLOR);
		g.fillRect(xPos, Y_POS, PADDLE_WIDTH, PADDLE_HEIGHT);
		g.setColor(Color.gray);
		g.drawRect(xPos, Y_POS, PADDLE_WIDTH, PADDLE_HEIGHT);
	}
	
	public static void main(String&#91;&#93; args){
		Ball b = new Ball(110, (Y_POS - (Ball.DIAMETER - 5)), 5, 5);
		Paddle p = new Paddle(110);
		for(int i = 1; i &lt;= PADDLE_WIDTH; ++i){
			b.setX(b.getX() + 1);
			System.out.println(p.hitPaddle(b));
		}
		System.out.println(p.hitPaddle(b));
	}
}</pre>
	<script type="text/javascript">mh_sh_highlight_all('java');</script>

</div>
 Now this class is reasonably simple. It starts with some constants (anything in capital letters). The constants basically say things about the class. The name of the constant generally will give you an understanding of what each does. Just in case I will explicitly describe them here:<br />
•	Y_POS : This is the Y position where the paddle will be located. The paddle only moves horizontally, so this remains constant.<br />
•	PADDLE_WIDTH: This is how wide the paddle will be. Since the paddle is being represented with the (x, y) position being the upper left hand corned. The width is how far to the right the paddle stretches. If the upper left corner is (x, y), then the upper right hand corner will be (x+PADDLE_WIDTH, y).<br />
•	PADDLE_HEIGHT: How tall the paddle is. If (x, y) is the top left point, then (x, y+PADDLE_HEIGHT) is the bottom left corner, and (x+PADDLE_WIDTH, y+PADDLE_HEIGHT) is the bottom right corner.<br />
•	PADDLE_COLOR: No real explanation for this constant, it’s simply the color of the paddle<br />
•	DELTA_X: This is how much in the x position to move the xPos variable (this isn’t really needed).<br />
Next, the instance variables. These dictate things about the class. Briefly, the xPos shows where the xPos in the (x,y) of the upper left hand corner—this changes. Score is the score the player has earned from breaking bricks (gain points), or missing the ball (lose points).<br />
This class has basic getters and setters which either set, or get a value to allow other classes to manipulate the paddle class. The class has a method which knows how to draw itself, given a Graphics2D object. One final important method is the one which really allows you to play the game. It takes as input some Ball, and determines whether or not the ball has hit the paddle. If the ball hits the paddle, it returns true, if not it returns false. The comment provides a more detailed explanation of how this method works. Most of the bounds detection takes a similar approach where it just checks first if the ball is hitting the object on the bottom or top, and then determines whether it was the top or bottom based on the relation of the y positions of the ball and the object.<br />
<br />
 That’s it for the paddle class. For the most part a very simple class, next lets look at the ball class.<br />
<br />
<div class="bbcode_container">
	<div class="bbcode_description">Java Code: </div>

	<pre class="brush: java">import java.awt.Color;
import java.awt.Graphics2D;

public class Ball {
	private int xPos, yPos;
	private int dX, dY;
	public static final int DIAMETER = 15;
	public static final Color BALL_COLOR = Color.black;
	
	public Ball(int xPos, int yPos, int dX, int dY){
		this.xPos	= xPos;
		this.yPos	= yPos;
		this.dX 	= dX;
		this.dY		= dY;
	}
	
	public void setX(int xPos){	this.xPos 	= xPos;	}
	public void setY(int yPos){	this.yPos	= yPos;	}
	public void setDX(int dX){	this.dX 	= dX;	}
	public void setDY(int dY){	this.dY		= dY;	}
	public int getX(){	return xPos;	}
	public int getY(){	return yPos;	}
	public int getDX(){	return dX;		}
	public int getDY(){	return dY;		}
	
	public void move(){
		xPos += dX;
		yPos += dY;
	}
	
	public void drawBall(Graphics2D g){
		g.setColor(BALL_COLOR);
		g.fillOval(xPos, yPos, DIAMETER, DIAMETER);
		g.setColor(Color.gray);
		g.drawOval(xPos, yPos, DIAMETER, DIAMETER);
	}
}</pre>
	<script type="text/javascript">mh_sh_highlight_all('java');</script>

</div>
 The ball class is actually easier than the paddle class. The ball class has instance variables for it’s location which are similar to that of the paddle class. It also has delta x and delta y (dX and dY). These two variables represent how much in the x or y the ball moves for each time unit. The move method actually makes the ball move one dX and one dY each time it is called. For an example, let’s say the ball starts at location 100, 100. If dX and dY are both 5, then after one call to move the ball will be located at 105, 105. This class has a couple of constants as well:<br />
•	DIAMETER: Simple enough, the diameter of the ball, the distance from one end to the other<br />
•	BALL_COLOR: The color of the ball<br />
The ball class also has getters and setters which aren’t going to be given much of an explanation, I will assume people are familiar with what getters and setters are, if you are not, read here: http://download.oracle.com/javase/tutorial/java/concepts/object.html<br />
<br />
Next lets look at the brick class, and the final class needed besides the drawing canvas.<br />
<div class="bbcode_container">
	<div class="bbcode_description">Java Code: </div>

	<pre class="brush: java"> 
import java.awt.Color;
import java.awt.Graphics2D;

public class Brick {
	public static final int BRICK_WIDTH = 60;
	public static final int BRICK_HEIGHT = 20;
	private int 	xPos, yPos;	
	private Type 	brickType;
	
	enum Type{
		ULTRA	(6, 700, Color.black),
		HIGH	(3, 150, Color.RED), 
		MEDIUM	(2, 100, Color.BLUE),
		LOW		(1, 50, Color.GREEN),
		DEAD	(0, 0, Color.WHITE);
		private int life;
		private Color color;
		private int points;
		
		Type(int life, int points, Color color){
			this.life = life;
			this.points = points;
			this.color = color;
		}
		public int getPoints(){	return points;	}
		public Color getColor(){	return color;	}
		public int getLife(){	return life;	}
	}
	
	public Brick(int xPos, int yPos, Type brickType){
		this.xPos = xPos;
		this.yPos = yPos;
		this.brickType = brickType;
	}
	
	public int getX(){	return xPos;	}
	public int getY(){	return yPos;	}
	public Type getBrickType(){	return brickType;	}
	
	public boolean hitBy(Ball b){
		//first check if it hits from the bottom or top
		if(b.getX() &lt;= (xPos + BRICK_WIDTH) &amp;&amp; b.getX() &gt;= xPos){
			//hit bottom
			if(b.getY() &lt;= (yPos + BRICK_HEIGHT) &amp;&amp; b.getY() &gt;= (yPos + (BRICK_HEIGHT / 2))){
				b.setDY(b.getDY() * -1);
				return true;
			}
			//hit top
			else if(b.getY() &gt;= (yPos - Ball.DIAMETER) &amp;&amp; b.getY() &lt; (yPos + (Ball.DIAMETER / 3))){
				b.setDY(b.getDY() * -1);
				return true;
			}
		}
		//determines if it from a side
		else if(b.getY() &lt;= (yPos + BRICK_HEIGHT) &amp;&amp; b.getY() &gt;= yPos){
			//hit right
			if(b.getX() &lt;= (xPos + BRICK_WIDTH) &amp;&amp; b.getX() &gt; (xPos + (BRICK_WIDTH - (Ball.DIAMETER / 2)))){
				b.setDX(b.getDX() * -1);
				return true;
			}
			//hit left
			else if(b.getX() &gt;= (xPos - Ball.DIAMETER) &amp;&amp; b.getX() &lt; (xPos + (Ball.DIAMETER / 2))){
				b.setDX(b.getDX() * -1);
				return true;
			}
		}
		return false;
	}
	
	public void decrementType(){
		switch(brickType.life){
			case 6:
			case 5:
			case 4:
				--brickType.life;
				break;
			case 3:
				brickType = Type.MEDIUM;
				break;
			case 2: 
				brickType = Type.LOW;
				break;
			case 1:
			default:
				brickType = Type.DEAD;
				break;
		}
	}
	
	public void drawBrick(Graphics2D g){
		g.setColor(Color.white);
		g.fillRect(xPos, yPos, BRICK_WIDTH, BRICK_HEIGHT);
		g.setColor(brickType.color);
		g.fillRect((xPos+2), (yPos+2), BRICK_WIDTH-4, BRICK_HEIGHT-4);
		g.setColor(Color.black);
		g.drawRect((xPos+2), (yPos+2), BRICK_WIDTH-4, BRICK_HEIGHT-4);
	}

	public boolean dead() {
		if(brickType.life == 0)
			return true;
		return false;
	}
}</pre>
	<script type="text/javascript">mh_sh_highlight_all('java');</script>

</div>
 This class is a bit more complex than the previous two classes.  First let’s talk about the constants this class has:<br />
•	BRICK_WIDTH: How wide the brick is, see the PADDLE_WIDTH constant <br />
•	BRICK_HEIGHT: How high the brick is, see the PADDLE_HEIGHT constant<br />
The brick has an (x,y) position similar to the paddle, except the brick does not move. Next is an enum called BrickType which is nested inside the class. The enum, like any enum has some constants which represent how hard it is to break some type of brick, and it also supplies it with a point amount to award and a color for the brick. Most of this is pretty self-explanatory. Each time the brick is hit, the points for the type are awarded to the player.  This enum also contains methods which allow you to view the variables of the type. For the most part I believe the enum is very self-explanatory and I will not get too in depth. If you have further questions about enums, please ask them in the comments.  The decrement type method is fairly simple and is to be called each time a brick is hit; this method drops from one type down to the next by using a simple switch statement. The logic is simple; it gets the life assigned with the type, and uses a switch statement on it. It then switches down to the next type based on the previous type. If the original type is MEDIUM, it moves to LOW, if it is HIGH, it drops down to MEDIUM. The Type enum also offers a DEAD brick which lets you know when to stop drawing a specific brick. There is a method which determines if you have killed a brick. This class also knows how to draw itself and the draw method is a bit more interesting the then previous classes. It contains a white rim, with a black edge to make different bricks easily distinguishable. It does this by first drawing a white filled rectangle, and then a slightly smaller colored filled rectangle, and finally a regular black rectangle.<br />
<br />
Now to finally hit on a more serious method, this method is a bit more complex (albeit not much more). It is responsible for a lot of the game. This is the method which determines if the ball hits the block, and also decides which side of brick was hit. The method I am speaking of is the hitBy method. It takes a Ball in as an argument and makes comparisons between the balls location and the bricks areas. This may not be the best approach for detecting collisions but I believe it does a fair job.<br />
Some background on how my logic worked when designing this method first. If the brick is a rectangle with the (x,y) coordinate marking the top left corner than the following points are also points which lie on the bricks perimeter:<br />
<div class="bbcode_container">
	<div class="bbcode_description">Java Code: </div>

	<pre class="brush: java"></pre>
	<script type="text/javascript">mh_sh_highlight_all('java');</script>

</div>
 That being said it may seem a little easier to work this method out. It is invaluable to visualize the brick and the ball for this method, and perhaps trying to solve it by hand (with drawings if necessary). Much of this method involves range checking. First you want to decide whether the ball is in the range (x, x+BRICK_WIDTH) if it is you know it has a similar x location compared to the ball. Now you want to see how close the ball is to the brick. This is done with the y location of the ball. If the y location of the ball is in range of (y+BRICK_HEIGHT) it has hit the brick from underneath, and the method changes the x direction of the ball, and returns true. If it is in range of the y position you know it hits the brick from the top, and can reflect the balls direction and return true. Reflecting the ball simply involves multiplying the current dX of the ball by -1. While this doesn’t necessary yield the greatest ball movement, it is the simplest approach. Now that we have determined whether the brick was hit on the top or bottom, we can determine if it hits the sides, and take the correct action. If the ball is in the range (x, x+BRICK_HEIGHT) we know it has the potential to hit the brick. This step inverses the previous step. Previously we checked the x range, then y, this time we start at the y range and move to the x. If it is in the y range, we determine where the x is. If the is in range of (x+BRICK_WIDTH) we can reflect the ball and return true. If it is in range of x, we return true and reflect again. I keep mentioning 'in range' to avoid confusion I would like to discuss briefly what I mean by this. I simply mean the x or y position of the ball is close to the x or y of what we are currently testing. Usually I allowed a bit of a buffer space to avoid problems in the animation by using a buffer greater than dX or dY. This method is a bit more complex, but it still isn't terribly hard to follow. Once again I must emphasize the importance of asking questions if you are unsure of something (or if I didn't come across too clear).<br />
<br />
Now that we have our components are written it’s time to use them in what is the actual game. The canvas class, this class is a bit more complex if you are unfamiliar to drawing on a canvas, but hopefully I will make it easy for you to understand. Here is the canvas class:<br />
<div class="bbcode_container">
	<div class="bbcode_description">Java Code: </div>

	<pre class="brush: java">import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.util.ArrayList;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

import breakout.Brick.Type;

public class Canvas extends JPanel implements ActionListener, MouseMotionListener, MouseListener, KeyListener {
	/**
	 * 
	 */
	private static final long serialVersionUID = -5699255769305413877L;
	public static final int HEIGHT = 600;
	public static final int WIDTH = 720;
	
	private int horizontalCount;
	private BufferedImage image;
	private Graphics2D bufferedGraphics;
	private Timer time;
	private static final Font endFont = new Font(Font.SANS_SERIF, Font.BOLD, 20);
	private static final Font scoreFont = new Font(Font.SANS_SERIF, Font.BOLD, 15);
	
	private Paddle player;
	private Ball ball;
	ArrayList&lt;ArrayList&lt;Brick&gt; &gt; bricks;
	
	/**
	 * Prepares the screen, centers the paddle and the ball. The ball
	 * will be located in the center of the paddle, and the paddle will
	 * be located on the center of the screen
	 * Sunde
	 * The bricks are displayed in columns across the screen with the 
	 * screen being split based on the width of an individual brick. 
	 * Each brick is stored in a temporary ArrayList, which is added
	 * to the classes ArrayList which contains all of the bricks.
	 */
	public Canvas(){
		super();
		setPreferredSize(new Dimension(WIDTH, HEIGHT));
		image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
		bufferedGraphics = image.createGraphics();
		time = new Timer(15, this);
		player = new Paddle((WIDTH/2)-(Paddle.PADDLE_WIDTH/2));
		ball = new Ball(((player.getX() + (Paddle.PADDLE_WIDTH / 2)) - (Ball.DIAMETER / 2)), 
				(Paddle.Y_POS - (Ball.DIAMETER + 10)), -5, -5);
		
		bricks = new ArrayList&lt;ArrayList&lt;Brick&gt; &gt;();
		horizontalCount = WIDTH / Brick.BRICK_WIDTH;
		for(int i = 0; i &lt; 8; ++i){
			ArrayList&lt;Brick&gt; temp = new ArrayList&lt;Brick&gt;();
			Type rowColor = null;
			switch(i){
				case 0:
				case 2:
					rowColor = Type.LOW;
					break;
				case 1:
				case 3:
				case 5:
					rowColor = Type.MEDIUM;
					break;
				case 4:
				case 6:
					rowColor = Type.HIGH;
					break;
				case 7:
				default:
					rowColor = Type.ULTRA;
					break;
			}
			for(int j = 0; j &lt; horizontalCount; ++j){
				Brick tempBrick = new Brick((j * Brick.BRICK_WIDTH), ((i+2) * Brick.BRICK_HEIGHT), rowColor);
				temp.add(tempBrick);
			}
			bricks.add(temp);
			addMouseMotionListener(this);
			addMouseListener(this);
			addKeyListener(this);
			requestFocus();
		}
	}
	
	@Override public void actionPerformed(ActionEvent e){
		checkCollisions();
		ball.move();
		for(int i = 0; i &lt; bricks.size(); ++i){
			ArrayList&lt;Brick&gt; al = bricks.get(i);
			for(int j = 0; j &lt; al.size(); ++j){
				Brick b = al.get(j);
				if(b.dead()){
					al.remove(b);
				}
			}
		}
		repaint();
	}

	/**
	 * Checks for any collisions, if the ball hits the upper wall, or the side
	 * walls it changes direction. If the ball goes below the paddle, the position
	 * of the ball gets reset and the player loses a life
	 */
	private void checkCollisions() {
		if(player.hitPaddle(ball)){
			ball.setDY(ball.getDY() * -1);
			return;
		}
		//first check if ball hit any walls
		if(ball.getX() &gt;= (WIDTH - Ball.DIAMETER) || ball.getX() &lt;= 0){
			ball.setDX(ball.getDX() * -1);
		}
		if(ball.getY() &gt; (Paddle.Y_POS + Paddle.PADDLE_HEIGHT + 10)){
			resetBall();
		}
		if(ball.getY() &lt;= 0){
			ball.setDY(ball.getDY() * -1);
		}
		
		//next handle collisions between bricks
		int brickRowsActive = 0;
		for(ArrayList&lt;Brick&gt; alb : bricks){
			if(alb.size() == horizontalCount){
				++brickRowsActive;
			}
		}
		
		for(int i = (brickRowsActive==0) ? 0 : (brickRowsActive - 1); i &lt; bricks.size(); ++i){
			for(Brick b : bricks.get(i)){
				if(b.hitBy(ball)){
					player.setScore(player.getScore() + b.getBrickType().getPoints());
					b.decrementType();
				}
			}
		}
	}
	
	/**
	 * Sets the balls position to approximately the center of the screen, and
	 * deducts a point from the user. If necessary, ends the game
	 */
	private void resetBall() {
		if(gameOver()){
			time.stop();
			return;
		}
		ball.setX(WIDTH/2);
		ball.setY((HEIGHT/2) + 80);
		player.setLives(player.getLives() - 1);
		player.setScore(player.getScore() - 1000);
	}
	
	private boolean gameOver() {
		if(player.getLives() &lt;= 1)
			return true;
		return false;
	}

	/**
	 *  Draws the screen for the game, first sets the screen up (clears it)
	 *  and then it begins by setting the entire screen to be white. Finally
	 *  it draws all of the bricks, the players paddle, and the ball on the 
	 *  screen
	 */
	@Override public void paintComponent(Graphics g){
		super.paintComponent(g);
		bufferedGraphics.clearRect(0, 0, WIDTH, HEIGHT);
		bufferedGraphics.setColor(Color.WHITE);
		bufferedGraphics.fillRect(0, 0, WIDTH, HEIGHT);
		player.drawPaddle(bufferedGraphics);
		ball.drawBall(bufferedGraphics);
		for(ArrayList&lt;Brick&gt; row : bricks){
			for(Brick b : row){
				b.drawBrick(bufferedGraphics);
			}
		}
		bufferedGraphics.setFont(scoreFont);
		bufferedGraphics.drawString(&quot;Score: &quot; + player.getScore(), 10, 25);
		if(gameOver() &amp;&amp;
				ball.getY() &gt;= HEIGHT){
			bufferedGraphics.setColor(Color.black);
			bufferedGraphics.setFont(endFont);
			bufferedGraphics.drawString(&quot;Game Over!  Score: &quot; + player.getScore(), (WIDTH/2) - 85, (HEIGHT/2));
		}
		if(empty()){
			bufferedGraphics.setColor(Color.black);
			bufferedGraphics.setFont(endFont);
			bufferedGraphics.drawString(&quot;You won!  Score: &quot; + player.getScore(), (WIDTH/2) - 85, (HEIGHT/2));
			time.stop();
		}
		g.drawImage(image, 0, 0, this);
		Toolkit.getDefaultToolkit().sync();
	}
	
	

	private boolean empty() {
		for(ArrayList&lt;Brick&gt; al : bricks){
			if(al.size() != 0){
				return false;
			}
		}
		return true;
	}

	@Override public void mouseMoved(MouseEvent e){
		player.setX(e.getX() - (Paddle.PADDLE_WIDTH / 2));
	}
	
	@Override public void mouseDragged(MouseEvent e){}
	
	@Override public void mouseClicked(MouseEvent e){
		if(time.isRunning()){
			return;
		}
		time.start();
	}
	
	public static void main(String&#91;&#93; args){
		JFrame frame = new JFrame();
		Canvas c = new Canvas();
		frame.add(c);
		frame.pack();
		frame.setResizable(false);
		frame.setVisible(true);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	@Override
	public void mousePressed(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseEntered(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseExited(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}
}</pre>
	<script type="text/javascript">mh_sh_highlight_all('java');</script>

</div>
 This class is quite larger than the rest, more than three times larger in fact. It is also a bit more complex since it is the code that essentially allows the game to play. I plan to start from the beginning and explain how each piece of this class works. <br />
The constants specify the size of the canvas, they are named HEIGHT and WIDTH, and I will let you figure out what each dictates &#61514;.<br />
The horizontalCount variable will be explained later, when it is necessary, for now just ignore it. The way I like to draw is via a BufferedImage and Graphics2D object (since I am far from an expert, this approach may not be the best. It is what I will use though). These two variables are set up in the constructor and work together well, you first clear the image of everything, then you draw what you want on the image, and finally you draw the image onto the JPanel. I have the class as a subclass of JPanel, which was my own naïve approach, as a challenge for you, I suggest removing this and getting it to work. Doing this allows the class to be more flexible—it will work on anything which can draw an object. The Timer object is what allows animation and it works quite simply. You supply the Swing Timer with a time period, and an action listener. The time period, x,  is in milliseconds and it will call the actionListener assigned to it every x milliseconds. In something like this, every x milliseconds, the ball will make a move, as will everything these which can move. The paddle will be repositioned, etc. Since x is in milliseconds, it makes sense to figure out how many frames per second there are. Since there are 1000 ms in one second, you find FPS with 1000/x. My timer uses 15 for x, so it produces ~67 frames per second. You can play around with the value of x and see how the game changes. In general, assuming nothing else changes, higher values of x will make the game animate slower, and smaller values will make it animate faster. <br />
<br />
The two Fonts are really unimportant at this point (and fairly unimportant later as well). They are predefined fonts to use for certain drawing scenarios—scoreFont will be used to draw the score, and endFont will be used when you win or lose the game.  The final thing the class needs are the “players”—the paddle, bricks, and ball. The Bricks are stared in an ArrayList of ArrayLists. This lends naturally to rows and columns, and I chose ArrayList over arrays for the simplicity of removing ‘dead’ bricks. <br />
<br />
The constructor of this class begins by initializing the important instance variables and sets the position of the ball, and paddle. The ball and paddle are located at the center on the x plane, and Y_POS on the y plane. The ball is slightly higher than the paddle. Now is where horizontalCount comes into play, it is used to create how many bricks will be in each row of bricks. It’s calculated as simply the WIDTH divided by the BRICK_WIDTH. It is helpful to ensure that WIDTH % BRICK_WIDTH == 0 (WIDTH is evenly divisible by BRICK_WIDTH) for the best view. The row of bricks are arbitrarily set at 8, and a double loop is set up. This nested loop fills the arrayList of ArrayLists with the proper items. It creates a temporary list in the first loop, and then fills this list in the second loop and adds it to the main list. The type of the brick is determines based on the row number via a switch statement, and each brick is positioned to the right BRICK_WIDTH units. Each new row of bricks is drawn lower BRICK_HEIGHT units.  Finally some listeners are added to allow the mouse input to be useful.  <br />
<br />
Earlier when I spoke of the Timer I talked about an actionListener which is ‘linked’ to it, this action listener is really the animation of the game, it is quite important. It checks collisions to determine if the ball hit something—the sides, the top, a brick, or the paddle. After checking for collisions it’s safe to assume the ball will be moving in the correct direction, and the ball is moved once via the balls move() method. Since it is possible for bricks to be dead it is important to check for this. The final part checks each brick to determine whether dead bricks exist, and if so, it removes them from the list. The action listener does not actually do any drawing it simply sets up conditions which will alter the view when the frame is redrawn. The changes will happen every 15 seconds, allowing a call to repaint to show the changes it just made.<br />
<br />
The checkCollisions method is what really allows the game to work properly. As it implies by the name, it checks to see if the ball hits anything. This method is called every 15 milliseconds thanks to the Swing Timer. When called this method first checks if the ball hits the paddle, and if it does, it changes the balls direction. The logic for checking for a paddle hit is in the paddle class and was explained earlier. If the ball does hit the paddle, the method returns to prevent strange behavior—like the ball bouncing off the paddle and a side wall at the same time. If the ball has not hit the paddle, it next checks whether any of the wall have been hit. If the ball hits the left or right wall, it is reflected in the x position (dX multiplied by -1). If it hits the top wall it reflects in the y direction (dY multiplied by -1), and it also checks if the ball has been missed by the paddle. If the ball is missed, the resetBall() method is called—this method will be explained shortly. The final step may seem a bit complex, but I assure you, it’s not. We don’t want to check for collision’s with every brick—while this is probably feasible, it’s a waste of resources, and it’s easy to avoid. We calculate how many bricks rows are currently active by declaring a local variable, and initializing it to 0. Then we begin looking through the bricks array list. For each array list in bricks, we test the size of the array list to the horizontalCount variable. Basically, if any list is at the max size, we skip past it, this way we don’t check for collisions on row 0, when row 8 hasn’t been broken through. Now that we attained how many intact rows there are, we begin another loop, if there are 0 rows intact, we test all the bricks available, otherwise we test the bricks from brickRowsActive-1 to the size of the bricks arrayList. We subtract one from brickRows active because it is very likely that row 7 will be full, and row 8 will be less than full. If we didn’t subtract 1, it would only check row 8, if for some reason the ball passed row 8 without hitting anything it would go through the remaining bricks. Try this and see for yourself. Surprisingly enough, the game won’t ever end because the initial size of the brickRowsActive variable will end up being bricks.size(), and no checking will be performed. Now that we figured that out, we will actually do our checking to see if bricks are hit. I use a for each loop here, for each brick in the ith arraylist, we will do collision detection on. The collision detection is all performed in the brick class, we simply call the method on each brick with the ball as the argument. When a brick is hit, two things must be done, first we add points to the player score—this is determined by the current brick type. Then we decrement the bricks type with the method decrementType in the brick class.<br />
<br />
The resetBall method was called in the previous method (checkCollisions), and now it is explained. The method first checks if the game is over, and if it does, it stops the Timer, which stops all animation. Before stopping the timer it decrements the players lives, which will make them 0. The gameOver() method returns true if the player has 1 or less lives left. Next, the resetBall method positions the ball near the center of the screen, lowers the players lives by 1, and reduces there score by 1000.</blockquote>

]]></content:encoded>
			<dc:creator>sunde887</dc:creator>
			<guid isPermaLink="true">http://www.java-forums.org/blogs/sunde887/93-breakout-tutorial.html</guid>
		</item>
		<item>
			<title>Book Recommendations</title>
			<link>http://www.java-forums.org/blogs/sunde887/74-book-recommendations.html</link>
			<pubDate>Mon, 20 Jun 2011 19:34:25 GMT</pubDate>
			<description>In this article I plan to create a quick, easy to locate post about good books that I have encountered. Feel free to comment and add your book...</description>
			<content:encoded><![CDATA[<blockquote class="blogcontent restore">In this article I plan to create a quick, easy to locate post about good books that I have encountered. Feel free to comment and add your book recommendations. I plan to include more than just Java books in this post. I will start with Java, moving onto c++, and other languages. The end of the post with books I have on my short list. These books will be finished shortly and I will put them here, and update my thoughts as the books are finished.<br />
<br />
<div style="text-align: center;"><font size="4"><i><b>Starting out - Which book to get?</b></i></font></div><br />
Beginning to learn java, or any programming language could seem difficult. Without a good book to start you may be asking &quot;How can anyone learn this stuff?&quot; It's true that a bad book will make learning the language very challenging. Sometimes even a good book that is above your skill level could make it very challenging. Hopefully with this book list you will more easily begin to program in Java. Knowing one language well also greatly helps learning other languages. I believe one of the first steps to learning to program is to set everything up. I find this to be one of the most challenging things for a beginner. What to download? How to use it? What should I use to edit my programs? Should I get an IDE, or use command line?<br />
<br />
For java, you want to download the JDK from the sun website. It's free, and fairly easy to install, I will also provide a great link for setting this up and running your very first program. Editing your programs will always be based on personal opinions. I personally enjoy using notepad++, and command line compiling, but you should decide what to use on your own.<br />
<br />
First, the link to setting everything up - <a href="http://www.thenewboston.com/?p=1047&amp;pOpen=tutorial" target="_blank" rel="nofollow">http://www.thenewboston.com/?p=1047&amp;pOpen=tutorial</a> - You can find many more interesting video tutorials at this links website, but the first is invaluable when it comes to setting up the JDK properly.<br />
<br />
Next, where to download an editor, some popular IDE's are Eclipse, and Netbeans. I will not cover how to install them since I use neither. I prefer notepad++, available here - <a href="http://notepad-plus-plus.org/" target="_blank" rel="nofollow">http://notepad-plus-plus.org/</a><br />
<br />
You may be asking &quot;When are you going to get into the actual books?&quot; Well now is the time to get into my recommendations.<br />
<br />
<div style="text-align: center;"><i><b><font size="3"><u>Java Books:</u></font></b></i></div><br />
There are a lot of truly great books out there -- possibly too many to know where to start. One of the highly recommended places to start, is the Oracle java tutorials. These tutorials are quite well written(since they are written by the java creators). The tutorials have simple examples which do a good job explaining the material. Sometimes the tutorials can be a bit challenging for beginners, but sticking with them will help you learn the language from the tutorials. <a href="http://download.oracle.com/javase/tutorial/reallybigindex.html" target="_blank" rel="nofollow">http://download.oracle.com/javase/tu...ybigindex.html</a><br />
<br />
<b><u>Head First Java:</u></b><br />
One of my absolute favorite books out there for learning java. The book is a smooth read, with light hearted talk and comedy mixed in. This book aims to teach you in a way that is simple to learn. They don't want to over complicate the already complicated process. This book covers a wide variety of topics very well. It doesn't get too in depth when it comes to the more challenging topics(threading, generics, networking), but it gives you a base from which to expand on. The book has thinking exercises for you to do, but not like you may be looking for. In this respect, the book could have improved, otherwise, the book is truly excellent.<br />
<a href="http://oreilly.com/catalog/9780596004651" target="_blank" rel="nofollow">http://oreilly.com/catalog/9780596004651</a> -- I recommend buying all books on amazon, it's quite cheap to get used books in great condition.<br />
<br />
<b><u>Thinking in Java:</u></b><br />
A good book, but it definitely requires you to understand the language a bit. I read this book as a complete beginner and was able to really learn a lot, but also, I had complaints. The author at times seems like he is writing for himself, not for beginners. If you stick with this book you will get a lot out of it. It covers many topics in depth, even many advanced topics(nio, threading, etc). The chapter on Strings in the book was excellent, as was the one on exceptions.<br />
<br />
The book also did a great job explaining some interesting things. One big thing is when making the compare, or compareTo  method. Many people take a naive approach and do something like<br />
<div class="bbcode_container">
	<div class="bbcode_description">Java Code: </div>

	<pre class="brush: java">public class Ex implements Comparable&lt;Ex&gt;{
  private int x;
  public int compareTo(Ex e){
    return x - e.x;
  }
}</pre>
	<script type="text/javascript">mh_sh_highlight_all('java');</script>

</div>
 This may look like a good enough approach, if the numbers are equal, it returns 0, if this is &lt; e, it returns a negative number, otherwise it returns a positive number. But what if you have one number that is really small, and one that is really large? For example, (-10000 and Integer.MAX_VALUE), if you subtract the numbers you will get a weird result. Wouldn't you expect -10000 to be less than Integer.MAX_VALUE? You would, but this will return that the negative number is actually larger. This error arises due to overflow.<br />
<br />
This is just one of many things Thinking in Java will teach you. It's a good book and well worth reading.<br />
<a href="http://www.mindview.net/Books/TIJ/" target="_blank" rel="nofollow">http://www.mindview.net/Books/TIJ/</a><br />
<br />
<b><u>Effective Java:</u></b><br />
This book is a bit more complex and shouldn't be a starting book, but should definitely be read. This is one of the best books I have read, it truly teaches you a lot and allows you to really think when designing your classes. The book is filled with items that you should try to adhere to. Each chapter covers a different type of items, one chapter works with object creating, things like using static factory methods rather than constructors, or using a builder when a class has a constructor with many different optional parameters.<br />
<br />
The book has a great chapter on Generics, which can really teach you a lot about generics and it shows you some good tips to keep in mind. This book is great in every way and I highly recommend it to anyone. This book should not be passed up.<br />
<a href="http://java.sun.com/docs/books/effective/" target="_blank" rel="nofollow">http://java.sun.com/docs/books/effective/</a><br />
<br />
<b><u>Java Concurrency in Practice:</u></b><br />
Another great book, but very challenging to understand at times. This is a book you need to really pay attention to and should not be your first book on programming. If you have a decent understanding of most of the basics and you are interested in threading, I suggest this book greatly. It teaches a complex topic very well with good examples.<br />
<a href="http://jcip.net/" target="_blank" rel="nofollow">http://jcip.net/</a><br />
<br />
<div style="text-align: center;"><b><i><u><font size="4">C++ Books:</font></u></i></b></div><br />
This section deals with some good beginner books on C++,  my experience with C++ isn't as great as it is with java so this section will be brief.<br />
<br />
<b><u>C++ Without Fear</u></b><br />
This is the second programming book I ever read. I read this book before any java books and it made my java life much easier. The book teaches you all the basics and really helps you understand how stuff happens. Consider reading this book if you are very new to programming and would like to learn C++. <br />
<a href="http://www.amazon.com/Without-Fear-Beginners-Guide-Makes/dp/0321246950" target="_blank" rel="nofollow">http://www.amazon.com/Without-Fear-B.../dp/0321246950</a><br />
<br />
<b><u>Accelerated C++</u></b><br />
This book is a bit more challenging and teaches many more advanced concepts in c++. It taught me some things I didn't even know exists. Looping through data structure with iterators, rather than a loop counter, and many other things. This is a great, short, easy to read book which covers a lot of topics in C++ very well. It does however; expect you to already have some familiarity with another similar language.<br />
<a href="http://www.acceleratedcpp.com/" target="_blank" rel="nofollow">http://www.acceleratedcpp.com/</a><br />
<br />
<b><u>Practical C++ Programming</u></b><br />
This book, like the other c++ books are very good and truly cover the language well. It emphasizes the importance of good programming style, it covers pointers, building classes, array, and many other things. It even covers how to use the preprocessor a bit. It has fairly good exercises at the end of each chapter and it is definitely well worth a read.<br />
<a href="http://oreilly.com/catalog/9781565921399" target="_blank" rel="nofollow">http://oreilly.com/catalog/9781565921399</a><br />
<br />
There are many other C++ books that are great, but I am not going to cover them right now.<br />
<br />
<br />
<div style="text-align: center;"><b><i><u><font size="4">Other Books:</font></u></i></b></div><br />
These books are just good books I like, some programming, some just interesting other books.<br />
<br />
<b><u>Code:</u></b><br />
This book is brilliant. It teaches you how to build a computer. It starts with the most basic concepts in computers, the binary system. With this system, everything in a computer can be done. It teaches you about logic gates and builds them up gradually. It shows you how the current flows through each different logic gate to produce either a 1 or 0 based on the correct inputs. It  builds these logic gates up to form many things, like adders. It eventually talks about how to build ram, and then moves onto transistors. In the book they explain very clearly how to build an entire computer, how to program it, how everything is executed in machine code, and many other topics. This book is a fun, mostly easy read, well worth buying.<br />
<a href="http://www.amazon.com/Code-Language-Computer-Hardware-Software/dp/0735611319" target="_blank" rel="nofollow">http://www.amazon.com/Code-Language-.../dp/0735611319</a><br />
<br />
<b><u>How to Design Programs:</u></b><br />
This book uses Dr. Scheme and a very good teaching approach. Dr. Scheme is a lisp like language and as such, uses lots of recursion. The book is truly amazing. It has many exercises, from simple, to excruciatingly difficult for a beginner. In this book you learn how to write programs to make fractals, like Sierpinski triangles, to some other advanced Generative recursion problems. One of the exercises is to write an AI search to solve the Missionaries and Cannibals problem. It also allows you to find all the permutations of some word. This book had some amazing feeling moments(those moments when you never expect to solve a problem and finally do).<br />
<br />
Great Book, and it's freely available at the following website: <a href="http://htdp.org/" target="_blank" rel="nofollow">http://htdp.org/</a><br />
<br />
<b><u>Surely you're joking Mr. Feynman</u></b><br />
This is not a programming book, it is instead a great book about Richard Feynman's life. It has funny stories from his life and shows how curious he was. It's a fun read and definitely interesting. Worth reading, and it's chap at amazon. <br />
<a href="http://www.amazon.com/Surely-Feynman-Adventures-Curious-Character/dp/0393316041" target="_blank" rel="nofollow">http://www.amazon.com/Surely-Feynman.../dp/0393316041</a><br />
<br />
Now a book I haven't read in entirety but I must recommend. It's a bit challenging, but I feel this book would be extraordinarily influential learning some very advanced topics. The book is from MIT and is named &quot;Structures and Interpretation of Computer Programs,&quot; and it uses Scheme, which is a lisp like language. A challenging read for sure, from the first chapter I have read, but well worth the challenge.<br />
Also, freely available here: <a href="http://www-mitpress.mit.edu/sicp/" target="_blank" rel="nofollow">http://www-mitpress.mit.edu/sicp/</a><br />
<br />
I hope this article is helpful to people, since this is not the first revision of the post I will provide a link to a previous post I have written, which will be similar to this, but different. Here is the link to that page: <a href="http://sunde887.wordpress.com/2011/05/01/helping-beginners-get-started/" target="_blank" rel="nofollow">http://sunde887.wordpress.com/2011/0...s-get-started/</a><br />
<br />
Another good link I have found some books that I am reading/going to read soon can be found at the following link to Stack Overflow.<br />
<a href="http://stackoverflow.com/questions/1711/what-is-the-single-most-influential-book-every-programmer-should-read" target="_blank" rel="nofollow">http://stackoverflow.com/questions/1...er-should-read</a><br />
<br />
As stated in the beginning, if you have anything that you feel should be added that I left out, please add a comment.</blockquote>

]]></content:encoded>
			<dc:creator>sunde887</dc:creator>
			<guid isPermaLink="true">http://www.java-forums.org/blogs/sunde887/74-book-recommendations.html</guid>
		</item>
		<item>
			<title>Recursion</title>
			<link>http://www.java-forums.org/blogs/sunde887/73-recursion.html</link>
			<pubDate>Mon, 20 Jun 2011 02:39:02 GMT</pubDate>
			<description>*Recursion: 
* 
 
Recursion is defined as: 
1. 	the act or process of returning or running back 
2. 	logic, maths  the application of a function to...</description>
			<content:encoded><![CDATA[<blockquote class="blogcontent restore"><b><div style="text-align: center;"><font size="4">Recursion:</font></div></b><br />
<br />
Recursion is defined as:<br />
1. 	the act or process of returning or running back<br />
2. 	logic, maths  the application of a function to its own values to generate an infinite sequence of values. The recursion formula  or clause  of a definition specifies the progression from one term to the next, as given the base clause f (0) = 0, f ( n  + 1) = f ( n ) + 3 specifies the successive terms of the sequence f ( n ) = 3 n <br />
<br />
In this article, I hope to make the reader have a basic understanding of what recursion is, and how it works. When programming there are indeed different types of recursion, there are iterative recursive processes, and simple recursive processes. Shortly I will explain the two in more depth, and provide some examples of the two. <br />
<br />
Recursion is simple, but can get quite complex. You are creating a method that is defined in terms of it's self. One of the simplest examples of a recursive process is calculating the factorial of a number. The factorial of a number is pretty easily understood and recognized. The factorial of some number n, is 1 * 2 * 3 ... n-1 * n. This can be directly translated into a recursive process quite easily. You can define the recursion in words like so:<br />
<br />
The factorial of a number n is either:<br />
<div style="margin-left:40px">1. if n is 0, the factorial is 1</div><div style="margin-left:40px">2. otherwise perform n * n - 1</div><br />
The first part in this simple definition is known as the termination condition. The termination condition is what ends the process. If not included it will cause infinite recursion. Much like a standard for loop has a condition, recursion does as well. If you created the following for loop<br />
<div class="bbcode_container">
	<div class="bbcode_description">Java Code: </div>

	<pre class="brush: java">for(int i = 0;; ++i)</pre>
	<script type="text/javascript">mh_sh_highlight_all('java');</script>

</div>
 It would loop indefinitely, since you provided no end condition. One of the key things to remember when writing a recursive method is to figure out what should end the method. How long should it continue calling itself recursively before finding an answer?<br />
<br />
Let's turn the definition of a factorial above into a running program. The method is simple and will return the int result of the computation.<br />
<div class="bbcode_container">
	<div class="bbcode_description">Java Code: </div>

	<pre class="brush: java">public class Factorial{
  /**
   * The method below computes the factorial of some number, n.
   * @param int
   */
  public int factorial(int n){
    if(n == 0) //this is the termination condition
      return 1; // when the condition is reached, 1 is returned.
    else{
      return n * factorial(n - 1); //notice the recursive call here
    }
  }
  public static void main(String&#91;&#93; args){
    Factorial f = new Factorial();
    int n = f.factorial(10);
    System.out.println(n);
    n = f.factorial(5);
    System.out.println(n);
  }
}</pre>
	<script type="text/javascript">mh_sh_highlight_all('java');</script>

</div>
 This is a very basic recursive method which I am using as an example. The applications of recursion can get much more complicated, and I intend to show some more powerful uses of recursion(although not too complex). When this method runs it first checks the termination condition, if it's met, the method returns an answer. If the condition is not met, it adds something to the stack and calls a new method.<br />
<br />
In java, when a method encounters another method, it gets pushed to the top of the stack and temporarily stops the original method until the new method is completed. Once the method being called finishes, the program picks up from where it left off. Since this simple recursive method calls itself n times, it pushes n items onto the stack, it continues pushing method calls onto the stack until the termination condition is met. Then it calculates the remaining things on the stack. An example easily illustrates how this works:<br />
<div class="bbcode_container">
	<div class="bbcode_description">Java Code: </div>

	<pre class="brush: java">factorial(5) 
5 * factorial(4)
5 * 4 * factorial(3)
5 * 4 * 3 * factorial(2)
5 * 4 * 3 * 2 * factorial(1)
5 * 4 * 3 * 2 * 1 * factorial(0) //Termination condition
5 * 4 * 3 * 2 * 1 * 1
5 * 4 * 3 * 2 * 1
5 * 4 * 3 * 2
5 * 4 * 6
5 * 24
120</pre>
	<script type="text/javascript">mh_sh_highlight_all('java');</script>

</div>
 The method reaches the final step <div class="bbcode_container">
	<div class="bbcode_description">Java Code: </div>

	<pre class="brush: java">return n * factorial(n - 1)</pre>
	<script type="text/javascript">mh_sh_highlight_all('java');</script>

</div>
 . so n is put on the stack and attempts to multiply, but it reaches a new method call which is pushed onto the stack and begins running. This repeats until the method reaches the termination condition and then it goes back and finishes evaluating all the multiplications on the stack.<br />
<br />
Another, possibly more elegant way to compute the factorial of some number requires that you keep a &quot;Running total&quot; of the current factorial. This method contains steps, where each step contains all the information to calculate the answer at that step. If you were to stop in the middle of the method and print the results, you could instantly restart from where you were. In the previous example, you would have to start the calculation from the beginning.<br />
<br />
This is known as an iterative recursive process, and here is what it looks like<br />
<div class="bbcode_container">
	<div class="bbcode_description">Java Code: </div>

	<pre class="brush: java">public class Factorial{
	public int factorial(int n){
		return factorial(n, 1);
	}
	public int factorial(int n, int soFar){
		if(n == 0) return soFar;
		return factorial(n - 1, (soFar * n));
	}
	public static void main(String&#91;&#93; args){
		Factorial f = new Factorial();
		int n = f.factorial(10);
		System.out.println(n);
		n = f.factorial(5);
		System.out.println(n);
	}
}</pre>
	<script type="text/javascript">mh_sh_highlight_all('java');</script>

</div>
 This method overloads factorial so you can pass in a single argument and that argument gets forwarded to another version of factorial(an iterative version).<br />
<br />
I believe in java both methods take up the same space. Either way the method is being continuously called. However; in other languages, like scheme, the amount of space required between the two methods is quite dramatically different. The amount of space for the first(recursive) method is O(n), the space depends on the amount of times the method is called. The second approach(iterative) has O(1) in terms of space. It's constant, at each step the value is known. Here is what the space required would look like in a language like scheme.<br />
<div class="bbcode_container">
	<div class="bbcode_description">Java Code: </div>

	<pre class="brush: java">factorial(5, 1)
factorial(4, 5)
factorial(3 20)
factorial(2 60)
factorial(1 120)
factorial(0, 120)
120</pre>
	<script type="text/javascript">mh_sh_highlight_all('java');</script>

</div>
 Each step &quot;remembers&quot; the value calculated so far.<br />
<br />
The amount of things recursion can do is vast. I believe it's almost safe to say that recursion can accomplish anything in programming(notice I said almost, I'm sure there there things recursion is incapable of).<br />
<br />
Recursion can do things like, sum an array, count the amount of items in said array, and do many other array based processing tasks. Here are a few<br />
<br />
<div class="bbcode_container">
	<div class="bbcode_description">Java Code: </div>

	<pre class="brush: java">interface Transformer{
	int transform(int n);
}</pre>
	<script type="text/javascript">mh_sh_highlight_all('java');</script>

</div>
 <div class="bbcode_container">
	<div class="bbcode_description">Java Code: </div>

	<pre class="brush: java">class Mult implements Transformer{
	int factor;
	public Mult(int factor){
		this.factor = factor;
	}
	public int transform(int n){
		return factor * n;
	}
}</pre>
	<script type="text/javascript">mh_sh_highlight_all('java');</script>

</div>
 <div class="bbcode_container">
	<div class="bbcode_description">Java Code: </div>

	<pre class="brush: java">public class ArrayUtil{
	private Transformer t;
	
	public ArrayUtil(Transformer t){
		this.t = t;
	}
	public int sumArray(int&#91;&#93; arr){
		return sumArray(0, arr);
	}
	public int sumArray(int index, int&#91;&#93; arr){
		if(index == arr.length) return 0;
		return arr&#91;index&#93; + sumArray(index + 1, arr);
	}
	
	public int countArray(int&#91;&#93; arr){
		return countArray(0, arr);
	}
	public int countArray(int index, int&#91;&#93; arr){
		if(index == arr.length) return 0;
		return 1 + countArray(index + 1, arr);
	}
	
	public void transformArray(int&#91;&#93; arr){
		transformArray(0, arr);
	}
	public void transformArray(int index, int&#91;&#93; arr){
		if(index == arr.length) return;
		arr&#91;index&#93; = t.transform(arr&#91;index&#93;);
		transformArray(index + 1, arr);
	}
	public static void main(String&#91;&#93; args){
		Transformer x = new Mult(10);
		int&#91;&#93; y = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
		ArrayUtil au = new ArrayUtil(x);
		System.out.println(au.sumArray(y));
		System.out.println(au.countArray(y));
		au.transformArray(y);
		for(int i = 0; i &lt; y.length; ++i){
			System.out.print(y&#91;i&#93; + &quot;, &quot;);
		}
		System.out.println();
	}
}</pre>
	<script type="text/javascript">mh_sh_highlight_all('java');</script>

</div>
 This may require a bit of explaining, the transformer interface and Mult class must be in different files, and it allows you to transform the array in many different ways. For example, if you wanted to add x to each element you can simply make the following class<br />
<div class="bbcode_container">
	<div class="bbcode_description">Java Code: </div>

	<pre class="brush: java">public class Adder implements Transformer{
  int amount;
  public Adder(int amount){
    this.amount = amount;
  }
  public int transform(int n){
    return n + amount; 
  }
}</pre>
	<script type="text/javascript">mh_sh_highlight_all('java');</script>

</div>
 You would then pass in a reference to this class to the ArrayUtil constructor. This uses the strategy pattern to make transform quite easily extensible to anything you can think of.<br />
<br />
The transform method is the only thing new here, it simply forwards to a so called &quot;alien method,&quot; the exact behavior is unknown, it can change to whatever the Transformer t requires it to do. The method really isn't too challenging though, it simply moves through the array recursively transforming each element of the array.<br />
<br />
<br />
There is many more complex things that can be done with recursion, and this &quot;complex&quot; example, is really quite trivial.<br />
<br />
You can do things from animating recursively, solving puzzles recursively, and drawing fractals recursively. If you would like to learn a lot more about recursion, I highly recommend you check out the following two books(both of which are freely available online). <br />
<br />
The first is &quot;How to Design Programs,&quot; available at HTDP.org<br />
<br />
The second is &quot;Structures and Interpretation of Computer Programs,&quot; available at <a href="http://www-mitpress.mit.edu/sicp/" target="_blank" rel="nofollow">http://www-mitpress.mit.edu/sicp/</a><br />
<br />
I hope this article was helpful and helped you learn something. Feel free to criticize any claims I may have made or offer corrections.</blockquote>

]]></content:encoded>
			<dc:creator>sunde887</dc:creator>
			<guid isPermaLink="true">http://www.java-forums.org/blogs/sunde887/73-recursion.html</guid>
		</item>
	</channel>
</rss>
