Вы находитесь на странице: 1из 30

Introduction to JAVA

This tutorial is not designed to teach a programming language or how to


program in Java but is intended to provide an introduction to Java and get
familiar with basic concepts of Java. This tutorial assumes that you have
taken computer science classes through CS 2308 or have equivalent
experience. Knowledge of any high level language and object oriented design
will also be extremely helpful.
TABLE OF CONTENTS

INTRODUCTION .................................................................................................................................... 3
KEY DIFFERENCES BETWEEN C++ AND JAVA: ................................................................... 3
A FIRST SIMPLE PROGRAM............................................................................................................ 4
A CLOSER LOOK AT PROGRAM ..................................................................................................... 5
DATA TYPES AND VARIABLES ...................................................................................................... 6
EXPRESSIONS ........................................................................................................................................ 7
CONTROL FLOW .................................................................................................................................... 9
INHERITANCE AND POLYMORPHISM..................................................................................... 10
PACKAGES AND INTERFACES...................................................................................................... 12
EXCEPTION HANDLING .................................................................................................................. 13
APPLETS .................................................................................................................................................. 15
USEFUL LINKS FOR JAVA:............................................................................................................. 16
REFERENCES ......................................................................................................................................... 16
APPENDIX A
CONVERTING C++ MAGIC 8 BALL TO JAVA (WITH A GUI)....................................... 16
APPENDIX B
EASIER LIFE THROUGH SWING: JFILECHOOSER ............................................................ 24
APPENDIX C
JAVAMAIL: WRITING A SIMPLE E-MAIL PROGRAM....................................................... 28
Introduction
Java is a high-level, third generation programming language, like C,
FORTRAN, Smalltalk, Perl, and many others. You can use Java to write
computer applications that crunch numbers, process words, play games,
store data or do any of the thousands of other things computer software can
do.

Key Differences between C++ and Java:


No pointers Just references –
Java has references but there are no pointers. This basically means there is
no way for you to directly access the memory that has been reserved for an
object except through the use of the object or primitive itself. It is possible to
have multiple objects of the same type referencing the same memory.
In C++ it is possible to have multiple object and primitive pointers pointing
at the same block of memory and for each to operate on it in a different way.

Java is Object-Oriented
In C++ you can have functions that are not attached to classes. The main
function in C++ is explicitly not attached to a class.
In Java, all function, including the main function, are attached to classes that
means within class. Everything is an object here.

Java is a Platform-Independent
When Java program is compiled; it produces a special format called byte
code and not executable code. Java bytecode is executed by Java run-time
system, which is called Java Virtual Machine. In its standard form, JVM is an
interpreter for bytecode. Java bytecode is exactly the same on every
platform. Only JVM needs to be implemented on every machine. Thus details
of JVM differ from platform to platform. The interpreter reads the byte code
and translates it into the native language of the host machine on the fly.
Since the byte code is completely platform independent, only the interpreter
and a few native libraries need to be ported to get Java to run on a new
computer or operating system. Thus due to JVM, Java becomes architecture
neutral.

Java is safe and simple


Java was designed from the ground up to allow for secure execution of code
across a network, even when the source of that code was not trusted and
possibly malicious.
Furthermore Java has strong typing. Variables must be declared, and
variables do not change types when you aren't looking. Casts are strictly
limited to casts between types when you are not loosing data. Thus you can
cast an int to a long but not an int to a String.
Java implements a robust exception handling mechanism to deal with both
expected and unexpected errors. The worst that an applet can do to a host
system is bringing down the runtime environment. It cannot bring down the
entire system.
Most importantly Java applets can be executed in an environment that
prohibits them from introducing viruses, deleting or modifying files, or
otherwise destroying data and crashing the host computer. A Java enabled
web browser checks the byte codes of an applet to verify that it doesn't do
anything nasty before it will run the applet. The biggest security issue in
computing today is bugs. Java, by making it easier to write bug-free code,
substantially improves the security of all kinds of programs.

Java is Multithreaded
Java is inherently multi-threaded. A single Java program can have many
different threads executing independently and continuously. Three Java
applets on the same page can run together with each getting equal time from
the CPU with very little extra effort on the part of the programmer.

Java has Garbage Collector


One of the most difficult tasks in C++ is keeping track of objects and then
deleting those to free up memory and prevent data leaks. In Java there is no
delete command because Java does memory garbage collection for free when
objects are no longer referenced. There is a slight performance decrease
associated with this service, but it greatly aides in providing reliable crash
free programs. There are constructors and these do allocate memory on the
heap, but this is transparent to the programmer.

Use of try and catch mandatory


For the most severe and common errors in Java the use of catch and try is
mandatory. It is built into Java’s grammar that these error checking
precautions must be present or else your program will not compile.
In C++, catch and try are also available, but are not mandatory.

A First Simple Program


Let’s start by compiling and running the short sample program.

/* This is a simple Java program*/


class HelloWorld {
public static void main (String args[]) {
System.out.println("Hello World!");
}
}

To write the code you need a text editor. You can use any text editor like
Notepad, Brief, emacs or vi. You should not use a word processor like
Microsoft Word or WordPerfect since these save their files in a proprietary
format and not in pure ASCII text. If you absolutely must use one of these,
be sure to tell it to save your files as pure text. Generally this will require
using Save As... rather than Save.

By convention, the name of source file should be same as name of the class
which contains main. Java is case sensitive.

Compiling the program


To compile the program, execute the compiler, javac, specifying the name of
the source file on the command line, as shown here:

C:\>javac HelloWorld.java

The javac compiler creates a file called HelloWorld.class that contains the
bytecode version of the program.
To run the program, you must run the Java Interpreter, called java and pass
the class name HelloWorld, as shown here:

C:\>java HelloWorld

When the program is run, following output is displayed: Hello World!

When java source code is compiled, each individual .class file is produced for
each class which contains its bytecode. So when you write java HelloWorld,
you are specifying the class file which interpreter needs to look for and
execute the code.

A closer look at Program

Let us look at several key features which are common to all Java programs.
/* This is a simple Java program*/

Java has 3 kinds of comments:


• As shown above –multiple line comment using /* */
• Simple line or inline comment - // This is a simple Java program
• Javadoc comment - /**
*@ author
*@ param
*@ return
* This is a simple Java program
*/
Java can produce documentation if javadoc command is used. It produces
series of HTML document from collection of java source files that have been
commented using certain tags e.g. author, param, etc. This HTML document
describes classes, methods, variables and constants contained in source files.
Then there is simple class keyword which can be preceded by abstract, final
or public.
• abstract class contains methods some of which are implemented and
some are empty ( e.g. sort() { })
• final class describes that a class have no subclasses.
• public class can be used and instantiated by all classes in the same
package.

main is a method in Java. Using some of the modifiers as shown below,


scope of a method can be restricted:
• public: anyone can call public method
• protected: only methods in the same package or of subclasses can
call protected method.
• private: only methods of the same class (not methods of subclass)
can call a private method.
• If none of above is used then the method can be called by objects of
classes in the same package.

Some additional modifiers:


• Abstract: a method declared as abstract will have no code and
appears only in abstract class. e.g. public abstract void setElement (int
i);
• final: final method can not be overridden by a subclass.
• static: static method is associated with a class itself and not with a
particular instance of class.
So our main is associated with HelloWorld class only and it won’t be
associated with any of its instance.
e. g. HelloWorld hw; //create object
hw.main (); is not allowed.
Constructor method has same name as class. It has no return value. An
abstract, static or final constructor is not allowed.

The argument passed as a parameter args to the main method are command
line arguments. It’s an array of Strings starting at args[0]. All parameters in
Java are passed by value that means a copy of variables is created and
passed.
Java provides a built-in static object, called System.out that performs output
to the standard output device. println prints the string followed by newline
character. System.out is an instance of java.io.PrintStream class.

Data types and variables


Java is strongly typed language. Every variable has a type, every expression
has a type and every type is strictly defined.
Java defines 8 simple types of data: byte, short, int, long, float, double, char,
boolean.
Type Identifier Bits Values
Character char 16 Unicode 2.0
8-bit signed integer byte 8 -128 to 127

Short signed integer short 16 (2 bytes) -32768 to 32767

Signed integer int 32 (4 bytes) -2,147,483,648 to +2,147,483,647

Signed long integer long 64 (8 bytes) maximum of over 1018

Real number (single precision) float 32 (4 bytes) Maximum of over 1038

Real number (double precision) double 64 (8 bytes) Maximum of over 10308

Boolean boolean true or false

Java variable is similar to C++ variable. It is defined by the combination of


an identifier, a type and an optional initializer.
Strings are enclosed in double quotes. e.g. “Hello”

Expressions
Expressions make use of literals explained above, variables and operators.
The Assignment Operator, the Dot Operator, Arithmetic Operator, Bitwise
Operator, Increment/Decrement Operator and Logical Operator are similar to
one in C++. Creating a new object involves the use of new operator.
Although, signature of method does not include the return type, Java does
not allow two methods with same signature to return different types.
Unlike C++, Java does not allow operator overloading.

String Concatenation
Strings can be composed using the concatenation operator (+).
e.g. String str1= “hello”;
String str2= “there”;
String str3=str1+str2;
would result into hellothere.
This shows how Java converts nonstring constants into strings, when they
are involved in a string concatenation operation.
Operator Precedence

postfix operators expr++ expr--

unary operators ++expr --expr +expr -expr ~ !

multiplicative */%

additive +-

shift << >> >>>

relational < > <= >= instanceof

equality == !=

bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

logical AND &&

logical OR ||

conditional ?:

assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

instanceof performs a test to see if a variable or object is the same type as a


class of built in variable type. The instanceof test returns true below because x is
an integer. e.g. int x;
if (x instanceof int)
System.out.println(“x is an integer!”);

Casting in Expressions
Casting is an operation that allows us to change the type of a variable.
Casting from int to double can be done but casting from double to int results
into lost of precision. Such implicit casts are not performed in Java. As we
saw earlier, implicit casting is done only with string concatenation.

Although, explicit casting of an object or base type to a string is not allowed.


e.g. String s= (String) 4.5; //Not Allowed
To perform such operation, instead we may use toString method.
e.g. String s= Integer.toString(4.5);
Control Flow

Decision statement (If and Switch) and loops (for-do, while-do, do-while) in
Java are similar to that of any other high level languages. break and continue
are also used similarly for restricted forms of jumps.

Arrays
Arrays in Java are similar to objects. It can be declared as follows:
int[ ] myArray;
myArray = new int[10];

int myArray[ ];

int[ ] betterArray = new int[10];

int[ ] nextArray = { 1 , 32 , 4, 54 ,3 ,65 ,34 ,343 };

int[ ][ ] twiceTheArray;
twiceTheArray = new int[10][10];

makeButtons( new String[] { "Back", "Next" } );

Another Example
As we have learned basic concepts of Java above, let us look at an example
which deals with Files. This program takes 2 command line argument as
input, adds them and write the output to a file.

import java.io.*;

public class Another


{
public static void main (String[] args) throws IOException

String fileName = "Myfile.dat" ;


String str;

System.out.println("You entered:" + args[0] );


System.out.println("You entered:" + args[1] );

str= args[0]+args[1];
System.out.println("You entered:" + str );

FileWriter fout;
try {
fout= new FileWriter (fileName);
fout.write(str);
fout.flush();

} catch (FileNotFoundException e)
{
System.out.println("Output file can not be opened");
}

}
}

Explanation – If we give 2 string input while running this program as input,


it will taken as argument 1 and argument 2. Data type of these arguments
would be always string. Notice here that + sign is used as a concatenation.
As built in class FileWriter is used, we need to import java.io.* package.
Object of FileWriter is created and concatenated string is written to file.
As FileWriter might throw an exception if file is not found, we need to put it
in try-catch block.

Inheritance and Polymorphism

Inheritance is one of the cornerstones of Java. A class that is inherited is


called superclass and one that does inheriting is called subclass. Subclass
inherits all the variables and methods defined by superclass and add its own
unique elements. However, subclass can not directly access the members of
superclass which are declared as private. Java’s solution to this problem is
the use of keyword super.
A subclass can call a constructor method in superclass by the use of super as
follows: super (parameter-list);
Super must always be first statement executed inside subclass’s constructor.

e.g. class A extends B {


int k;
A (int x, int y, int z, int w) {
super (x, y, z); //call superclass constructor
k=m;
}
}

Here we have subclass A which inherits superclass B. Notice the use of java
keyword extends which signifies the inheritance. In the constructor of class
A, constructor of superclass is called. Remember that x, y, and z are private
in superclass.
Second form of super acts somewhat like this, except it always refers to the
superclass of subclass. e.g.
class A { int k; }
class B extends A {
int k;
B(int m, int n) {
super.k = m; //k in A
k = n; //k in B
}
}

super always refers to the superclass immediately above the calling class.

Dynamic dispatch
When a method in subclass has same name and type signature as a method
in superclass then method in subclass is called to override method in
superclass. Now when a overridden method is called from subclass, it always
refer to subclass version. Superclass method is hidden.
Dynamic method dispatch is the mechanism by which a call to overridden
methods is resolved at run-time. Using dynamic dispatch Java implements
run-time polymorphism. e.g.
class A {
void print() {
System.out.println (“I am within A”);
}
}
class B extends A {
void print() { //overridden print
System.out.println (“I am within B”);
}
}

class C extends A {
void print() { //overridden print
System.out.println (“I am within C”);
}
}

class Dispatch {
public static void main (String args[]) {
A a = new A(); //object of type A
B b = new B(); //object of type B
C c = new C(); //object of type C
A r; //reference of type A

r = a; //r refers to object of superclass A


r.print();

r=b;
r.print();
r = c;
r.print()’
}
}

Ouput of program will be:


I am within A
I am within B
I am within C

Explanation – when a superclass method is overridden, and different types


of objects are referred to through a superclass reference, then java
determines which method to execute at run time depending on the type of
object referred to that time.
Overridden methods in java are similar to virtual functions in C++.

Java does not allow multiple inheritance for the sake of simplicity. Thus one
subclass can extend only one superclass. However. Multiple inheritance can
be implemented using interfaces about which we will learn below.

Abstract Class
Remember abstract class we talked above. Abstract class can be inherited by
another subclass. but it needs to implement all the methods in that interface
because some of the methods might not be implemented. This is the reason
that an abstract class can not be instantiated using new operator.

Packages and Interfaces


The java language takes a general and useful approach to the organization of
classes into programs. Every public class is defined in separate file with
extension .java. A set of all relevant classes, all defined in a common
subdirectory called a Package. Every file in a package starts with the line:
package <package-name>;

Using Other Packages


In java, we can use classes that are defined in other packages using dot
operator. e.g. public boolean Temperature (TA.Measures.Thermometer
thermometer, int temp);. Here TA is package, Measures is subpackage and
Thermometer is class of this package. As you can see, as we come to low
level in hierarchy, we become specific.

The import command


We can use import command similar to include command.
import <Package-name>.<class-name>;
We can import whole package as follows: import <package-name>.*;

Thus in any file hierarchy of these declaration would be e.g.


package student;
import TA.Measures;
class MeasureTemp {
public boolean Temperature (TA.Measures.Thermometer thermometer, int
temp) { ….} }

Interfaces

Interface is just declaring prototype. e.g. consider we want implement stack


of interger objects.

public interface Stack {


public int size();
public boolean isempty();
public int top();
public void push();
public int pop();
}
Save this file as Stack.java

Interfaces must be public. Now a class can implement this interface the way
it wants. But that class must implement all the methods declared in the
interface. So general form will be:
class A implements Stack {…..}
or it can be class A extends B implements Stack {….}

However, one interface can extend as many interfaces it wants. This is how
multiple inheritance is achieved. e.g.
Public interface X extends Y, Z {….}
Here Y and Z are interfaces which are inherited by X.
Now class W can implement X so that it obtains methods of X, Y as well as Z.

Exception Handling
An exception is abnormal condition which occurs in code at run time. There
are errors about which we can not do except returning gracefully displaying
error message. But we can handle exception manually.
All exception types are subclass of the built in class Throwable. Exception is
subclass of Throwable. This class is used for exception conditions that user
programs should catch. Then subclass of Exception is RuntimeException.
Exceptions of this type are automatically defined for the programs that we
write and include things such as divide by zero and invalid array indexing.

Throwing exception
Exceptions can be generated by java run time system or can be manually
generated. Java exception is an object which is thrown in the method
caused an error. That method catches the exception or passes it on and
exception is handled. e.g. if we try to delete 10th element from array of 5
elements, the code may throw a BoundryViolationException as follows:
If (insertIndex () > size ()) {
throw new
BoundryViolationException (“no element at this index”);

The throws clause


When a method is declared, it is appropriate to specify the exception it might
throw. It let Java compiler know which exception to prepare for. e.g.
public void insertIndex () throws BoundryViolationException {…..}
Thus this exception can be handled somewhere else and not necessarily
catch in this methods only.
e.g. public class BoundryViolationException extends RuntimeException {
public BoundryViolationException (String e) {
super (e);
}
}

Here this exception is handled by RuntimeException class.

Catching Exception
If an exception is to be handled in the method itself then we put the code of
method in try block and have control flow to jump to a predefined catch
block. After catch block, if finally block is not defined then control goes to
first statement after last line of the entire try-catch block. e.g.

int index = Integer.MAX_VALUE;


try {
String s = max[index];
}
catch (BoundryViolationException bve) {
System.out.println (“the index” + index +” is outside of the array”);
}

If this code does not catch a thrown exception, the flow of control will exit
and go to the method that called this method. If it’s not catching this
exception then it will jump to part which called this code and so on.
Eventually, if no code catches exception, Java runtime exception catches
exception.
Applets
Applets are small applications that are accessed on internet server,
transported over the internet, automatically installed, and run as part of web
document.
A Simple Applet Example

import java.awt.*;
import java.applet.*;

public class Myapplet extends Applet {

public void init() { //initialize the applet


System.out.println("Hello Sweden!");
}
}

Closer look at Applet


This applet begins with two import statements. Applet interacts through the
AWT (Abstract Window Toolkit) classes and not through consol-based I/O
classes. AWT contains support for a window-based, graphical interface.
Another imports applet package which contains the class Applet. All the
applets created must be subclass of Applet.
To execute an applet in a web browser, there need to be a HTML text file
which contains the appropriate APPLET tag like shown below.

<html>
<applet code ="Myapplet.class" width=300 height =100>
</applet>
</html>

Save it in file Myapplet.html. init() method is used to initialize the applet.


For applet you have 2 files, Myapplet.java and Myapplet.html
Compile using javac Myapplet.java. This will create class file.
To view applet, appletviewer Myapplet.html
Notice that Applet does not have main() method.

Java was designed to allow for secure, platform independent, software


execution, which is a big advantage in heterogeneous educational computing
environments. Java allows use of pointers but restricts potentially dangerous
programming styles, such as pointer arithmetic and arbitrary array indexing.
In addition, Java provides protection at several layers such as use of private
variables and methods. It has an extensive collection of meaningfully named
error conditions. It has simple built-in mechanism for memory management
and garbage collection. Finally, it contains simple constructs for various kinds
of computing such as multiprocessing, network computing and graphical user
interfaces.
Useful Links for Java:
Sun’s Java Homepage:
http://java.sun.com/

Getting Java:
http://java.sun.com/j2se/1.4.2/download.html

Sun’s Java Tutorial:


http://java.sun.com/docs/books/tutorial/index.html

Free Java Text Book (Excellent Source)


http://math.hws.edu/javanotes/index.html

Installing Java:
http://java.sun.com/j2se/1.5.0/install.htm

REFERENCES
The complete Reference Java2 by Herbert Schildt
Data Structures and Algorithms in Java by Goodrich and Tamassia

Appendix A

Converting C++ Magic 8 Ball to Java (with a GUI)


The idea behind this program is to allow a person to ask the magic 8-ball
program a question and get one of the responses that you could get from a
standard magic 8-ball. The C++ version of the code is displayed below:

#include <iostream.h>
#include <string>
#include <time.h>

using namespace std;

//Function Prototypes
int roll(int die, int numberRolls);

int main()
{
//variable declarations
char userContinueAnswer;
int randomIndex = 0;
int startCount = 0;
int newCount = 0;
string question;
string answer[6] = {"Yes","No","Try Again Later","Maybe","Most Definately"
,"Absolutely Not"};

cout << "Magic 8 Ball Program\n\n";

while( userContinueAnswer != 'N' && userContinueAnswer != 'n' )


{
cout << "Enter the question you want to ask the magic 8 ball
below:\n\n";
cin >> question;
cin.ignore(2000,'\n');
cout << "\nThe magic 8 ball is considering...\n";

for(int i = 0; i < 8; i++)


{
startCount = clock();
while( ((newCount-startCount) / CLOCKS_PER_SEC) < 1)
{newCount = clock();}

if ( i < 7)
cout << ".\n";
else
cout << "The Magic Eight Ball Predicts:\n\n";
}

randomIndex = roll(6,1)-1;
cout << answer[randomIndex] << "\n\n";

cout << "Would you like to ask the eight ball another question?\n"
<< "(Y/N):";
cin >> userContinueAnswer;

cout /*<< "\n: " << userContinueAnswer */<< "\n\n";

system("PAUSE");
return 0;
}

//This function will generate a random number x, where start*numberRolls


<= x <= end*numberRolls
//Each die roll is treated as a separate event. This gives us the correct
probability curve.
//i.e. rolling a 10 or an 11 on 3d6 is more likely then a 3 or 18.
int roll(int die, int numberRolls)
{
int sum = 0;

for( int i = 0; i < numberRolls; i++)


sum = sum + (int)((double)rand()/((double)RAND_MAX+1)*die)+1;

return sum;
}

The first step is to convert this program into an equivalent Java


program.

First we need to change the C++ library includes into Java import
statements:

Change: Into:
#include <iostream.h> import java.io.*;
#include <string> import java.util.*;
#include <time.h> import java.math.*;

using namespace std;

Next, we need to make a class that will contain all of our functions
since we cannot have free standing functions in Java. Also main
needs an instantiation of the class in it.

Change: Into:
//Function Prototypes class Magic8BallGUI
int roll(int die, int numberRolls); {
final int numAnswers = 5;
int main()
{ public static void main(String[]
args)
{
Magic8BallGUI myBall;
myBall = new Magic8BallGUI();

Also we need to change the C++ type “string” into the java
equivalent “String.” Follow that by changing the cout statement into
a System.out.println call:
Change: Into:
string question; String question;
string answer[6] = {"Yes","No","Try String answer[6] = {"Yes","No","Try
Again Later","Maybe","Most Again Later","Maybe","Most
Definately" Definately"
,"Absolutely ,"Absolutely
Not"}; Not"};

string question; String question;


cout << "Magic 8 Ball Program\n\n"; System.out.println("Magic 8 Ball
Program\n\n");

From here on out, when you see a cout statement, replace it with a
System.out.println statement.

Immediately following the System.out.println statement, add these


lines:

InputStreamReader is = new InputStreamReader(System.in);


BufferedReader bis = new BufferedReader(is);

These lines are necessary in Java to get complex input from the command
line. The InputStreamReader “wraps” the System.in stream and then is
wrapped itself by the Buffered Reader. A Buffered Reader gives us access to
a large number of input functions that will make getting input easier. Trying
to read from a Buffered Reader can cause an exception, so Java code must
added to handle that. On the plus side, the Buffered Reader takes care of
many formatting issues, so the ignore statement or something similar is not
needed.

Let use the Buffered Reader to get the user’s question:

Change: Into:
cin >> question; try {question = bis.readLine();}
cin.ignore(2000,'\n'); catch( Exception e){ System.exit(0);
}

Next, we convert the C++ specific time call into Java time calls. Note
that Java allows you to directly call the System to get the current
time.

Change: Into:
startCount = clock(); startCount =
while( ((newCount-startCount) / System.currentTimeMillis();
CLOCKS_PER_SEC) < 1) while( ((newCount-startCount) /
{newCount = clock();} 1000) < 1)
{newCount =
System.currentTimeMillis();}

Next convert the C++ random function call into a Java random
function call. Both of these are function calls that are user created.

Change: Into:
randomIndex = roll(6,1)-1; randomIndex =
myBall.randomIndex(myBall.numAnswers);

Next we need to change how we get the user’s response as to


whether they wish to continue or not. The first character is read to
get the user’s response, and then a line is read to clear out the input
buffer. Immediately following these statements the while loop ends.

Change: Into:
cin >> userContinueAnswer; try {userContinueAnswer=
(char)is.read();}
cout /*<< "\n: " << catch( Exception e){ System.exit(0); }
userContinueAnswer */<< "\n\n";
try {bis.readLine();} catch( Exception
} e)
{ System.exit(0); }

System.out.println(userContinueAnswer
+ "\n");
}

For our last modification we must change the C++ random function
into a Java random function. Notice that Java has built in functions
and objects for handling random number generation. This code goes
immediately after the code above and ends the class.

Change: Into:
System("PAUSE"); }//end of main
return 0;
} int randomIndex(int range)
{
if ( range <= 0 )
//This function will generate a random return 0;
number x, where start*numberRolls <=
x <= end*numberRolls Random generator = new
//Each die roll is treated as a seperate Random();
event. This gives us the correct return generator.nextInt(range);
probability curve.
//i.e. rolling a 10 or an 11 on 3d6 is }
more likely then a 3 or 18.
int roll(int die, int numberRolls)
{ }//end of class
int sum = 0;

for( int i = 0; i < numberRolls; i++)


sum = sum +
(int)((double)rand()/((double)RAND_MA
X+1)*die)+1;

return sum;
}

Save this file as “Magic8BallGUI.java”


Compile and execute the program.

Your code should look something like the listing below:

mport java.io.*;
import java.util.*;
import java.math.*;

class Magic8BallGUI
{

final int numAnswers = 5;

public static void main(String[] args)


{

//varaible declarations
Magic8BallGUI myBall;
myBall = new Magic8BallGUI();
String answer[] = {"Yes","No","Try Again Later","Maybe","Most
Definately"
,"Absolutely Not"};
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader bis = new BufferedReader(is);
char userContinueAnswer = 'Y';
int randomIndex = 0;
long startCount = 0;
long newCount = 0;
String question;
System.out.println("Magic 8 Ball Program\n\n");

while( userContinueAnswer != 'N' && userContinueAnswer != 'n' )


{
System.out.println("Enter the question you want to ask the magic 8 ball
below:\n\n");
try {question = bis.readLine();} catch( Exception e){ System.exit(0); }

System.out.println("\nThe magic 8 ball is considering...");

for(int i = 0; i < 8; i++)


{
startCount = System.currentTimeMillis();
while( ((newCount-startCount) / 1000) < 1)
{newCount = System.currentTimeMillis();}

if ( i < 7)
System.out.println(".");
else
System.out.println("The Magic Eight Ball Predicts:\n");
}

randomIndex = myBall.randomIndex(myBall.numAnswers);
System.out.println(answer[randomIndex] + "\n");

System.out.println("Would you like to ask the eight ball another


question?");
System.out.print("(Y/N): ");
try {userContinueAnswer = (char)is.read();} catch( Exception e){
System.exit(0); }
try {bis.readLine();} catch( Exception e){ System.exit(0); }

System.out.println(userContinueAnswer + "\n");

int randomIndex(int range)


{

if ( range <= 0 )
return 0;
Random generator = new Random();
return generator.nextInt(range);

To finish this program off we would like to make use of Java’s


extensive GUI capabilities to handle all user input and system output.

Add these statements to your imports:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

Next, add these statements to your main function before any of the other
functions:

int response = 0;

//Setup GUI Options


try{UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName() );}
catch( Exception e){System.exit(0);}

JFrame myFrame = new JFrame();


JPanel myPane = new JPanel();
JProgressBar myBar = new JProgressBar(0,20000000);
JLabel myLabel = new JLabel("The eight ball is carefully considering your
question");

myPane.setLayout(new FlowLayout());
myPane.add(myLabel);
myPane.add(myBar);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.add(myPane);
myFrame.pack();

The first statement once again sets the “look and feel” of the system to be as
much like the current OS as possible. The next four statements create the
GUI elements that we will be using to display our GUI. Finally, we add the
GUI elements to a pane, and then place the pane inside the frame; like a
pane of glass inside a window frame. Finally we “pack” the frame to make it
ready for display by the JVM.
The rest of the main function has radically shrunk and changed due to the
GUI so just copy and paste this code to replace the while loop and the code
following the while loop in the main function.

while( response == 0 )
{

JOptionPane.showMessageDialog(null,"Welcome to the Magic Eight Ball


Program");
JOptionPane.showInputDialog(null,"Please enter your question:","Magic 8
Ball",JOptionPane.QUESTION_MESSAGE);

myFrame.setVisible(true);

for(int i = 0; i < 20000000; i++)


myBar.setValue(i);

myFrame.setVisible(false);

randomIndex = myBall.randomIndex(myBall.numAnswers);
JOptionPane.showMessageDialog(null,answer[randomIndex]);
response = JOptionPane.showConfirmDialog(null,"Would you like to ask
the Magic 8 Ball Another Question?" ,"Another
Fortune?",JOptionPane.YES_NO_OPTION
,JOptionPane.QUESTION_MESSAGE);

}
System.exit(0);

} // end of main

Save, compile, and run. Notice that with a GUI the program has shrunk
considerably and it looks much better. Also Note that the
JOptionPane.ShowMessageDialog function call can be done without being
predeclared. It also shows the window that asks whether the user would like
to continue along with an option for yes or no. If the user selects “Yes” the
dialog returns 0, and if the user selects “No” it returns 1.

Appendix B

Easier Life through Swing: JFileChooser

The idea behind this program is to show how a simple event can be
processed using Swing, as well as showing how Swing’s built in graphical
interfaces make your life much easier.
Below is the code for the file “fileScroll.java” which has been provided for
you. Compile and run the program to get a feel for how it works.

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class fileScroll extends JFrame implements ActionListener{

//these GUI elments declared globally for the class


JTextArea myText;
JFileChooser fc;
JButton bt01;

//Main
public static void main(String ar[]){
JFrame f=new fileScroll();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(640,400);
f.setVisible(true);
}

//Constructor
fileScroll()
{
//Take advantage of the JFrame constructor
super("File Viewer");

//Setup GUI Options

try{UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName() );}
catch( Exception e){System.exit(0);}

//declare GUI elements

try{

//Initialize Elements

myText = new JTextArea(18,60);


myText.setText("No file selected");
fc=new JFileChooser();

bt01=new JButton("Open File to View");


bt01.setMnemonic('O');
bt01.setActionCommand("Open");
bt01.addActionListener(this);

Container c=getContentPane();
JPanel p1=new JPanel();
p1.add(bt01);
p1.add(myText);
c.add(p1);
}
catch ( Exception e) {}
}

public void actionPerformed(ActionEvent ae)


{
try
{

if(ae.getActionCommand()=="Open")
{
int fd=fc.showOpenDialog(fileScroll.this);

if(fd==JFileChooser.APPROVE_OPTION)
{
int count = 0;
boolean eof = false;
String text = "";
String line = "";
File myFile = fc.getSelectedFile();
BufferedReader myReader = new BufferedReader(new
FileReader(myFile.getPath() ) );

while(!eof)
{
line = myReader.readLine();
if (line == null || count == 18)
eof = true;
else
{
count++;
if ( line.length() < 59)
text = text + line + '\n';
else
text = text + line.substring(0,39) + '\n';
}
}
myText.setText(text);
}
}
}
catch(Exception ex){}

}
}

The first thing to notice is that the fileScroll class extends (inherits from)
JFrame and implements the ActionListener interface. This gives this class a
JFrame GUI for free and the blueprint for adding GUI “events”.

Next, notice the call of super(“File Viewer”) in the class’s constructor. This
calls the super class’s constructor, or in other words JFrame’s constructor.
This means that everything we need to do in our constructor is already done
in JFrame’s constructor, so we call its constructor rather then duplicating the
code.

Also important is the fc=new JFileChooser line. The JFileChooser graphical


element is entirely responsible for the file browsing window that appears in
the program when you want to choose a file. This saves you a tremendous
amount of work.

These lines:

bt01.setMnemonic('O');
bt01.setActionCommand("Open");
bt01.addActionListener(this);

Set up three things on the JButton bt01. The setMnemonic command allows
users to press Alt-O to activate the button. The setActionCommand sets the
event generated by this button being pressed to “Open”. Finally the
addActionListener(this) command adds an action listener to the button that
“listens” for events.

This brings us to the actionPerformed function which processes


events/signals and performs actions based on what signal it received. It
catches the “Open” signal and immediately opens the JFileChooser that we
created earlier.

If the user did not hit the “Cancel” button in the JFileChooser screen, a call is
made to fc.getSelectedFile() which returns a File object that represents the
file the user chose in the JFileChooser. A few lines later we create a
FileReader wrapped by a BufferedReader to get input from the file. The call
myFile.getPath() is very useful because it handles returning a file path string
that will work in the given operating system.
Appendix C

JAVAMAIL: Writing a simple e-mail program


This program allows you to send e-mail via the Javamail libraries. The code
listed below is contained in the file “email.java”.

/*
* Created on Apr 4, 2005
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/

/**
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class email


{
String from = "lh1037@txstate.com";
String recipient = "null@txstate.com";
String subject = "We want you!";
String cc = "null2@txstate.edu";
String body = "Eat More Pudding!";

//The session object keeps track of information about your current


connection.
Session mySession;

//The message object is a JavaMail Message Object the provides e-mail


functionality
Message mess;

public void SendMessage()


{

//set properties to send the mail


Properties prop = new Properties();
prop.put("mail.txstate.edu","mailhost");
//get a session with defaults and verbose output
mySession = Session.getDefaultInstance(prop,null);
mySession.setDebug(true);

try
{

//create the message using our newly created session


mess = new MimeMessage(mySession);

//Only InternetAddress Objects can be using in messsages so we need to


//incapsulate the strings we made eariler

//from
mess.setFrom(new InternetAddress(from));

//to and CC
InternetAddress toAddr = new InternetAddress(recipient);
InternetAddress ccAddr = new InternetAddress(cc);
mess.addRecipient(Message.RecipientType.TO, toAddr);
mess.addRecipient(Message.RecipientType.CC, ccAddr);

//subject
mess.setSubject(subject);

//message body
mess.setText(body);

//this command actually sends the message using the Transport Layer in
//a network model
Transport.send(mess);

}
catch( Exception e)
{ e.printStackTrace(); System.exit(0); }

public void addOn()


{
for(int i = 0; i < 100; i++)
body = body + " Join Today! Eat More Pudding! ";
}

public static void main(String[] args)


{
email myEmail = new email();
myEmail.addOn();
myEmail.SendMessage();
}

This program has many things going on in it, but first we will compile and run
the program. Make two modifications before this, change the cc and
recipient strings to your personal txstate e-mail address. Run the program,
and then check your e-mail. If this program will not compile, make sure that
you have installed Enterprise Java on your system because JavaMail requires
Enterprise Java libraries.

The first object that is created in the program is a session. This is analogous
to an internet session if you have done internet programming. It keeps track
of all the information related to your connection to the internet.

Next we create a properties object and add our mail host to the properties.
This mail host is where we will be sending our message so it can be
forwarded for delivery. Our session will use this property to route our e-mail.

We create a message object next that uses our session object to create a
message of the default mime type. After initializing the message with data
about the recipient, the sender, etc… we send the message to the TCP/IP
transport using the Transport.send(mess) call.

Вам также может понравиться