Post Reply 
 
Thread Rating:
  • 0 Votes - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Using java classes in Jython
12-26-2009, 12:41 AM
Post: #1
Using java classes in Jython
It is very easy to use java classes in jython. I will give you two quick examples. The first example I will import the Random class and random a number from 0-5

first you need to import that class like you do any other class in python.

Code:
from java.util import Random

Now that the Random class is import it lets initialize it. In java you would do
Random rand = new Random();
Here is how it is done in jython
Code:
rand = Random()

I would say that is even more easier then java! Now you can use it just like you would in java. This following line will print the random number to the screen;
Code:
print(rand.nextInt(6))

Now I want to do some number formatting! So lets import that DecimalFormat class that java uses.

Code:
from java.text import DecimalFormat

Next we need to initialize the class
Code:
df = DecimalFormat("$0.00")

If you already know java you would know that this initialization will format any number with $ and any range of number to the . and only 2 number after the decimal for precision. A side you can use double quotes are single quotes it doesn't matter.

Ok now lets format a number
Code:
print(df.format(3))
The result is $3.00

That is pretty much it! I like how I can build gui appz easier in python using java swing class Smile
Visit this user's website Find all posts by this user
Quote this message in a reply
12-26-2009, 02:05 AM
Post: #2
RE: Using java classes in Jython
Interesting tut. Very good random() function !

"I dont know with what weapons World War 3 will be fought with, but i know World War 4 will be fought with stones and sticks" - Albert Einstein
Visit this user's website Find all posts by this user
Quote this message in a reply
12-26-2009, 02:38 AM
Post: #3
RE: Using java classes in Jython
yea python has a built in random module import random. You can use either or. I was just showing a example the java way Tongue
Visit this user's website Find all posts by this user
Quote this message in a reply
02-06-2010, 05:09 PM
Post: #4
RE: Using java classes in Jython
(12-26-2009 02:38 AM)codecaine Wrote:  yea python has a built in random module import random. You can use either or. I was just showing a example the java way Tongue

Java also has a Generator class that is not static like Math class.
Find all posts by this user
Quote this message in a reply
Post Reply 


Forum Jump:


 Quick Theme: