*
*
|
|
Simple Code Examples
We present some simple programs in Java and Python, so you can
see how the languages compare. This type of document is
useful when you want to use your knowledge of one language to
learn another.
BTW, the Python
Library Reference is very well written, and is probably the
single best book to learn Python from.
Print out a multiplication table
Java Version
|
int num = 11; // Change this number to set the times table
for (int i=1; i<=num; i++)
System.out.println(i + " x " + num + " = " + i * num); |
Output
1 x 11 = 11
2 x 11 = 22
3 x 11 = 33
4 x 11 = 44
5 x 11 = 55
6 x 11 = 66
7 x 11 = 77
8 x 11 = 88
9 x 11 = 99
10 x 11 = 110
11 x 11 = 121
JSP Version
|
<%
int num = 11; // Change this number to set the times table
for (int i=1; i<=num; i++) {
%><%=i%> x <%=num%> = <%=i*num%><br><%
} %> |
Python Version
|
num = 11
for x in range(1, num+1):
print repr(x), "x", repr(num), "=", repr(x*num) |
Print out all multiplication tables
Java Version
|
for (int i=1; i<=12; i++) {
System.out.println("*** " + i + " Times Multiplication Table ***");
for (int j=1; j<=12; j++) {
System.out.println(i + " x " + j + " = " + i * j);
}
System.out.println();
} |
Output
Similar to the previous example, but much longer
Python Version
|
for i in range(1,13):
print "*** ", repr(i), " Times Multiplication Table ***"
for j in range(1, 13):
print repr(j), "x", repr(i), "=", repr(i*j) |
Zoom...
The previous examples were code fragments, made into complete
programs by Zamples. This example is a complete program.
You can tell by looking at the value of the pull-down in the Zamplizer:
it says 'Java 1.4 Class' instead of 'Java 1.4 Fragment'.
The sample program must have a main() method in order
to run.
|
public class Car {
public void drive() {
System.out.println("zooooooom...");
}
public static void main(String[] args) {
Car car = new Car();
car.drive();
}
} |
Output
zooooooom...
Penance for Chocolate Monsters
Java Version
|
System.out.println("<h3>Scroll down to see all the output</h3>");
String indent = "";
int inc = 1;
int marginLimit = 20;
for (int i=0; i<100; i++) {
System.out.println(indent + "I promise not to eat all the chocolate");
if (indent.length()==marginLimit)
inc = -1;
else if (indent.length()==0)
inc = 1;
if (inc>=1)
indent += " ";
else
indent = indent.substring(1);
} |
Output
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
I promise not to eat all the chocolate
Python Version
|
print "<h3>Scroll down to see all the output</h3>"
indent = ""
inc = 1
marginLimit = 20
for i in range(0,101):
print indent, "I promise not to eat all the chocolate"
if len(indent)==marginLimit:
inc = -1
elif len(indent)==0:
inc = 1
if inc>=1:
indent += " "
else:
indent = indent[1:] |
Ambivalent Greeting
The following program has an equal chance of wishing you a nice
or a lousy day.
Java Version
| |
<% if (Math.random()<0.5) { %>
Have a <B>nice</B> day! <%
} else { %>
Have a <B>lousy</B> day! <%
}
%> |
Sample output
Have a nice day! Python Version
|
import random
if random.random()<0.5:
print "Have a <B>nice</B> day!"
else:
print "Have a <B>lousy</B> day!" |
System Properties
If the Security Manager permits, the following code fragment
will list all of the system properties, beginning with the name
of the operating system that Zamples is running under.
Java Version
|
System.out.println("<h3>" + System.getProperty("os.name") + "</h3>");
boolean encode = false; // set true to see non-printable characters
Properties props = System.getProperties();
for (Enumeration enum = props.propertyNames(); enum.hasMoreElements();) {
String name = (String) enum.nextElement();
String value = (String)props.get(name);
try {
System.out.print("<b>" + name + "</b> = " +
((encode) ?
URLEncoder.encode(value, "UTF8") :
value) + "<br>");
} catch (UnsupportedEncodingException uee) {
System.err.println(uee.getMessage());
}
} |
Sample output, with encode set to false:
Windows 2000
java.runtime.name = Java(TM) 2 Runtime Environment, Standard Edition sun.boot.library.path = D:\jdk1.3\jre\bin java.vm.version = 1.3.0-C java.vm.vendor = Sun Microsystems Inc. java.vendor.url = http://java.sun.com/ path.separator = ; java.vm.name = Java HotSpot(TM) Client VM file.encoding.pkg = sun.io java.vm.specification.name = Java Virtual Machine Specification user.dir = D:\Java\jakarta-tomcat-3.2.1\bin java.runtime.version = 1.3.0-C java.awt.graphicsenv = sun.awt.Win32GraphicsEnvironment os.arch = x86 java.io.tmpdir = D:\DOCUME~1\ADMINI~1.NEW\LOCALS~1\Temp\ line.separator =
java.vm.specification.vendor = Sun Microsystems Inc. java.awt.fonts = os.name = Windows 2000 java.library.path = [snipped] java.specification.name = Java Platform API Specification java.class.version = 47.0 os.version = 5.0 user.home = D:\Documents and Settings\Administrator.NEWBORN user.timezone = America/Los_Angeles java.awt.printerjob = sun.awt.windows.WPrinterJob file.encoding = Cp1252 java.specification.version = 1.3 tomcat.home = D:\Java\jakarta-tomcat-3.2.1 user.name = Administrator java.class.path = [snipped] java.vm.specification.version = 1.0 java.home = D:\jdk1.3\jre user.language = en java.specification.vendor = Sun Microsystems Inc. awt.toolkit = sun.awt.windows.WToolkit java.vm.info = mixed mode java.version = 1.3.0 java.ext.dirs = D:\jdk1.3\jre\lib\ext sun.boot.class.path = [snipped] java.vendor = Sun Microsystems Inc. file.separator = \ java.vendor.url.bug = http://java.sun.com/cgi-bin/bugreport.cgi sun.cpu.endian = little sun.io.unicode.encoding = UnicodeLittle user.region = US sun.cpu.isalist = pentium i486 i386
If encode is changed to true, the non-printable
characters become visible.
|
System.out.println("<h3>" + System.getProperty("os.name") + "</h3>");
boolean encode = true; // set true to see non-printable characters
Properties props = System.getProperties();
for (Enumeration enum = props.propertyNames(); enum.hasMoreElements();) {
String name = (String) enum.nextElement();
String value = (String)props.get(name);
try {
System.out.print("<b>" + name + "</b> = " +
((encode) ?
URLEncoder.encode(value, "UTF8") :
value) + "<br>");
} catch (UnsupportedEncodingException uee) {
System.err.println(uee.getMessage());
}
} |
Sample output, with encode set to true:
Windows 2000
java.runtime.name=Java(TM) 2 Runtime Environment, Standard Edition
sun.boot.library.path=C:\J2SDK_Forte\jdk1.4.0\jre\bin
java.vm.version=1.4.0-b92
java.vm.vendor=Sun Microsystems Inc.
java.vendor.url=http://java.sun.com/
path.separator=;
java.vm.name=Java HotSpot(TM) Client VM
file.encoding.pkg=sun.io
user.country=US
sun.os.patch.level=Service Pack 2
java.vm.specification.name=Java Virtual Machine Specification
user.dir=C:\Program Files\Microsoft Office\Office
java.runtime.version=1.4.0-b92
java.awt.graphicsenv=sun.awt.Win32GraphicsEnvironmen
java.endorsed.dirs=C:\Java\jakarta-tomcat-4.0\bin;C:\Java\jakarta-tomcat-4.0\common\lib
os.arch=x86
java.io.tmpdir=C:\Java\jakarta-tomcat-4.0\temp
line.separator=
java.vm.specification.vendor=Sun Microsystems Inc.
user.variant=
java.naming.factory.url.pkgs=org.apache.naming
os.name=Windows 2000
sun.java2d.fontpath=
java.library.path=[snipped]
java.specification.name=Java Platform API Specification
java.class.version=48.0
java.util.prefs.PreferencesFactory=java.util.prefs.WindowsPreferencesFactory
os.version=5.0
user.home=C:\Documents and Settings\Administrator.CHLOE
user.timezone=GMT-10:00
catalina.useNaming=true
java.awt.printerjob=sun.awt.windows.WPrinterJob
file.encoding=Cp1252
java.specification.version=1.4
catalina.home=C:\Java\jakarta-tomcat-4.0
user.name=Administrator
java.class.path=[snipped]
java.naming.factory.initial=org.apache.naming.java.javaURLContextFactory
java.vm.specification.version=1.0
sun.arch.data.model=32
java.home=C:\J2SDK_Forte\jdk1.4.0\jre
java.specification.vendor=Sun Microsystems Inc.
user.language=en
awt.toolkit=sun.awt.windows.WToolkit
java.vm.info=mixed mode
java.version=1.4.0
java.ext.dirs=C:\J2SDK_Forte\jdk1.4.0\jre\lib\ext
sun.boot.class.path=[snipped]
java.vendor=Sun Microsystems Inc.
catalina.base=C:\Java\jakarta-tomcat-4.0
file.separator=\
java.vendor.url.bug=http://java.sun.com/cgi-bin/bugreport.cgi
sun.cpu.endian=little
sun.io.unicode.encoding=UnicodeLittle
sun.cpu.isalist=pentium i486 i386
Python Version
The standard Python libraries don't provide an htmlencode()
function, so we slimmed the code down a bit.
|
import os
print "<h3>", os.name, "</h3>"
for e in os.environ:
print "<b>", e, "</b>=", os.environ[e] |
Add new code samples here
If you have code samples that don't fit into any of the topics above which you would like to contribute,
please put them here.
We'll sort them out into their own sections as appropriate later.
date problems
Purpose: teste
Description: teste |
<table>
<tr>
<td><form action='http://zamples.com/JspExplorer/index.jsp' method=post class=formInput target='TomcatMain'>
<input type=hidden name=cmd value='<html> <body> <%        java.util.Date hoje = new java.util.Date();     Format df = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss");     String data_hora = df.format(hoje);          String sep = "-";     Calendar cal = new GregorianCalendar();     String data_acesso = ""+ cal.get(Calendar.YEAR)+sep+                                     cal.get(Calendar.MONTH)+sep+                                     cal.get(Calendar.DAY_OF_MONTH); %> <br> Seu IP de origem : <%=request.getRemoteAddr()%><br> A data calculada e : <%=data_acesso%><br> A data formatada : <%=data_hora%><br> </body> </html>'>
<input type=hidden name=imports value='import java.text.*; import java.util.*;'>
<input type=hidden name=applet value=''>
<input type=hidden name=format value='0'>
<input type=hidden name=pre value='true'>
<input type=hidden name=stylesheet value='http://zamples.com/StyleSheet.css'>
<input type=submit value='Try It!' class=formInput>
</form></td>
<td><pre><html> <body> <%        java.util.Date hoje = new java.util.Date();     Format df = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss");     String data_hora = df.format(hoje);          String sep = "-";     Calendar cal = new GregorianCalendar();     String data_acesso = ""+ cal.get(Calendar.YEAR)+sep+                                     cal.get(Calendar.MONTH)+sep+                                     cal.get(Calendar.DAY_OF_MONTH); %> <br> Seu IP de origem : <%=request.getRemoteAddr()%><br> A data calculada e : <%=data_acesso%><br> A data formatada : <%=data_hora%><br> </body> </html></pre></td>
</tr>
</table>
|
date problems
Purpose: see how the dates are different.
Description: see the dates are different |
<html>
<body>
<%
java.util.Date hoje = new java.util.Date();
Format df = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss");
String data_hora = df.format(hoje);
String sep = "-";
Calendar cal = new GregorianCalendar();
String data_acesso = ""+ cal.get(Calendar.YEAR)+sep+
cal.get(Calendar.MONTH)+sep+
cal.get(Calendar.DAY_OF_MONTH);
%>
<br>
Seu IP de origem : <%=request.getRemoteAddr()%><br>
A data calculada e : <%=data_acesso%><br>
A data formatada : <%=data_hora%><br>
<table>
<tr>
<td><form action='http://zamples.com/JspExplorer/index.jsp' method=post class=formInput target='TomcatMain'>
<input type=hidden name=cmd value='<html> <body> <%        java.util.Date hoje = new java.util.Date();     Format df = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss");     String data_hora = df.format(hoje);          String sep = "-";     Calendar cal = new GregorianCalendar();     String data_acesso = ""+ cal.get(Calendar.YEAR)+sep+                                     cal.get(Calendar.MONTH)+sep+                                     cal.get(Calendar.DAY_OF_MONTH); %> <br> Seu IP de origem : <%=request.getRemoteAddr()%><br> A data calculada e : <%=data_acesso%><br> A data formatada : <%=data_hora%><br> </body> </html>'>
<input type=hidden name=imports value='import java.text.*; import java.util.*;'>
<input type=hidden name=applet value=''>
<input type=hidden name=format value='0'>
<input type=hidden name=pre value='true'>
<input type=hidden name=stylesheet value='http://zamples.com/StyleSheet.css'>
<input type=submit value='Try It!' class=formInput>
</form></td>
<td><pre><html> <body> <%        java.util.Date hoje = new java.util.Date();     Format df = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss");     String data_hora = df.format(hoje);          String sep = "-";     Calendar cal = new GregorianCalendar();     String data_acesso = ""+ cal.get(Calendar.YEAR)+sep+                                     cal.get(Calendar.MONTH)+sep+                                     cal.get(Calendar.DAY_OF_MONTH); %> <br> Seu IP de origem : <%=request.getRemoteAddr()%><br> A data calculada e : <%=data_acesso%><br> A data formatada : <%=data_hora%><br> </body> </html></pre></td>
</tr>
</table>
</body>
</html>
|
Print Multiplication Tables.
Purpose: This code can be used to print out a multiplication table of the form:
2 X 1 = 2
2 X 2 = 4....and so on...
Description: This code can be used to print out multiplication tables. |
public class Multiply {
public static void main(String args[]) {
int number = 9; //Just change this number to generate for a new number.
for(int i=1;i<=10;i++) {
System.out.println(number +" X "+i+" = "+(number*i));
}
}
}
|
|
| to add a new posting or reply to an existing posting. |
|
|