Following on from our first lesson where we created our ‘Hello World’ application we will see what else we can do with a simple Java application, then we will convert our ‘Hello World’ application to an applet and deploy it on a Web Page.
Lets start.
Cut 'n paste or type this program into your editor.
/* Lesson 2 */
/** This is our weight application */
class weight
{
public static void main(String[] arguments)
{
int lbs = 90;
System.out.println("Ally McBeals weight is now " +
lbs +
" lbs.");
}
}
Now what is new in this program?
We have declared a variable called lbs and it is an integer (a number to the laymen) and our output consists of concatenated strings and the lbs variable.
Compile the application typing:
javac weight.java from the DOS prompt if you are using Win 9x or the Command Prompt from Win NT.
When you have no compilation errors then run it using java weight also from the DOS prompt if you are using Win 9x or the Command Prompt from Win NT.
You should see the output as
‘Ally McBeals weight is 90 lbs.’.
You may disagree with what I think she may weigh so what we are now going to do is pass some arguments to the application with what you think she may weigh.
Cut 'n paste or type this program into your editor.
/* Lesson 2 */
/** This is our weight2 application */
class weight2
{
public static void main(String[] arguments)
{
int lbs = 0;
if (arguments.length > 0)
lbs = Integer.parseInt (arguments[0]);
System.out.println("Ally McBeals weight " +
"is now " +
lbs + " lbs.");
}
}
Now what is new in this program.
We check if we have passed any arguments to the application by using the line ‘if (arguments.length > 0)’ and when then use ‘lbs = Integer.parseInt (arguments[0])’ to set the value of the variable lbs to the parameter that we used on the command line.
Compile the application using
javac weight2.java.
When you have no compilation errors then run it using
java weight2 77.
You should see the output:
‘Ally McBeals weight is 77 lbs.’.
Try it for yourself.
Now lets convert our weight application to a java applet.
/* Java 101 - Lesson 2 */
/** This is our weightapplet applet */
public class weightapplet extends java.applet.Applet
{
int lbs;
public void init()
{
lbs = 90;
}
public void paint(java.awt.Graphics g)
{
g.drawString("Ally McBeals weight is "
+ lbs + " lbs.",5,50);
}
}
Compile the applet using
javac weightapplet.java
Applets cannot be tested using the java interpreter tool. You have to put them on a web page and view them in one of two ways.
Use a web browsers such as the current versions of Mozila Fire Fox or Netscape Navigator or MS Internet Explorer
Type the following line:
ENTER THE HTML APPLET CODE
appletviewer weightapplet.htm
and our weight estimate will appear in the viewer. We will discuss applets in more detail later...
No comments:
Post a Comment