Voting

Category

real language

Bookmarking

Del.icio.us Digg Diigo DZone Earthlink Google Kick.ie
Windows Live LookLater Ma.gnolia Reddit Rojo StumbleUpon Technorati

Language Java

(exception oriented)

Date:09/08/05
Author:Jarek Ratajski
URL:n/a
Comments:1
Info:http://java.sun.com
Score: (3.37 in 133 votes)
/**
 * 99 Bottles in Java - Exception Oriented Programming :-)
 * This program abuses concept of exceptions. 
 * notice: it does not use any loops (for, while) or if statements
 *
 * use java 1.4 or newer
 * @author Jarek Ratajski 
 */
public class EOP99Bottles
{
    /**
     * this main method is very simple - 
     * only throws exception and prints stack trace
     * would You suspect it is 99 bottles program ? :-) 
     */
    public static void main(String[] args)
    {
	try
	{
	    throw new BottleException(1, null);
	}
	catch (Exception e)
	{
	    e.printStackTrace();
	}
    }
    
    private static class BottleException extends Exception
    {
	private final int cnt;
	/** 
	 * notice beauty of this signature: object that may throw exception of 
	 * its own type during its creation !!!
	 */
	public BottleException(int i, BottleException c)
	throws BottleException
	{
	    super(c);
	    this.cnt = i;
	    try
	    {
		int a  = 03 / (99-i);
		throw new BottleException(i+1, this);
	    }
	    catch (ArithmeticException e)
	    {
		//deliberately
	    }
	}
	
	public  void printStackTrace()
	{
	    System.out.println(cnt+" Bottle(s) of beer on the wall,"+cnt+"bottle(s) of beer");
	    System.out.println("Take one down and pass it around,");
	    System.out.println((cnt-1)+" bottle(s) of beer on the wall");
	    try
	    {
		getCause().printStackTrace();
	    }
	    catch (NullPointerException npe)
	    {
		//deliberately
	    }
	    
	}
    }
    
}

Download Source | Write Comment

Alternative Versions

VersionAuthorDateCommentsRate
object-oriented versionAnonymous04/20/0514
bytecode-version with loaderTilo Dickopp05/23/069
Java 5.0 object-oriented versionKvols11/19/053
Singing with Java Speech APIKevin Seifert05/04/061
standard versionSean Russell04/20/0510

Comments

>>  Robert Hayes said on 10/20/05 03:40:08

Robert Hayes Stick it in whatever class you want:

public static final String BEER = " BOTTLES OF BEER";
public static final String BEER_WALL = BEER + " IN THE WALL";

public static void bottleCounter() {
for (int i = 99; i > 0;) {
System.out.println(
i + BEER_WALL + ", " + i + BEER + "."
+ "TAKE ONE DOWN AND PASS IT ARROUND " + --i +
BEER_WALL);
}
}

Download Source | Write Comment

Add Comment

Please provide a value for the fields Name, Comment and Security Code.
This is a gravatar-friendly website.
E-mail addresses will never be shown.
Enter your e-mail address to use your gravatar.

Please don't post large portions of code here! Use the form to submit new examples or updates instead!

Name:

eMail:

URL:

Security Code:
  
Comment: