![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
The Oblivious One
Join Date: May 2005
Location: Ontario, Canada
Posts: 641
Rep Power: 4
![]() |
Jython
I don't know if there is an interest (especially in my seemingly random threads), but I just came across jython, and I think it's quite cool.
Basically, to test out making a package in Java, I wrote a simple class for a guessing game (my favorite hello-world type program).
package com.hakuch.guess;
import java.util.Random;
/**
*A number guessing game.
*
*This class provides the means to play a simple guessing game, with methods
*that allow a client to make a guess towards the number, and have access
*to key properties such as the secret number itself (read-only), and the
*number of guesses that were made.
*@author Jesse H-K
*/
public class NumberGame {
private int attempts;
private int number;
/**
*@param start The starting number in the range
*@param end The ending number in the range
*@throws IllegalArgumentException When start is greater then end.
*/
public NumberGame(int start, int end) throws IllegalArgumentException {
if(start > end)
throw new IllegalArgumentException("Invalid range given.");
Random rand = new Random();
int temp = rand.nextInt((end - start));
number = temp + start + 1;
attempts = 0;
}
/**
*Make a guess towards the secret number.
*@param guess The number to guess.
*@return true if a correct guess is made, false otherwise.
*/
public boolean makeGuess(int guess) {
++attempts;
if(guess != number) {
if(guess > number)
System.out.println("Too high!");
else if(guess < number)
System.out.println("Too low!");
return false;
}
else {
System.out.println("Correct!");
return true;
}
}
/**
*Get attempts.
*@return The number of attempts made so far.
*/
public int getAttempts() {
return attempts;
}
/**
*Get number.
*@return The secret number.
*/
public int getNumber() {
return number;
}
}When I heard about jython being able to intereact with java classes, I got curious, and wrote this tiny jython program:
from com.hakuch.guess import *
ng = NumberGame(1, 100)
while 1:
x = int(raw_input("Enter guess: "))
if(ng.makeGuess(x)):
break
print "You guessed the number (%d) in %d guesses." % (ng.getNumber(), ng.getAttempts())Now, I may just be excited, and you may all be rolling your eyes at the blabbering youngster, but I think this is really neat (and exactly the reason why I like programming so much) .
__________________
Dr. Zoidberg: [ecstatic] I'm going to a movie... with FRIENDS! |
|
|
|
|
|
#2 |
|
Sexy Programmer
|
pretty kool!
__________________
I would love to change the world, but they won't give me the source code! |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|