Vous êtes sur la page 1sur 92

California State Polytechnic University Department of Electrical and Computer Engineering

Java (ECE429) Lab Manual Lin Summer 2006

Preface:................................................................................................................................ 4 Lab 1 Hello World .............................................................................................................. 5 1.1 Lab Assignment Hello World application in JDK .................................................... 6 1.2 Lab Assignment Hello World Application Variations.............................................. 7 1.3 Hello World Application in IDE eclipse................................................................... 7 1.4 Hello World Applet in JDK ...................................................................................... 7 1.5 Hello World Applet in eclipse .................................................................................. 8 Lab 2 Control Structure: Exponential Function.................................................................. 9 2.1 Lab Assignment: Exponential Function.................................................................. 10 Lab 3 Complex Numbers .................................................................................................. 11 3.1 Lab Assignment Class Complex............................................................................. 12 Lab 4 Using Eclipse Debugger ......................................................................................... 14 Lab 4.1 Using Debugger to Locate a Problem in class Complexs multiply method... 22 Lab 5: Compute n factorial and big factorials .................................................................. 23 Lab 6: Animation.............................................................................................................. 27 Lab 7 GUI: 8 puzzles ........................................................................................................ 29 Lab 7.1 A moving button.............................................................................................. 31 Lab 7.2 Write the GUI program for 8 puzzles movement ............................................ 31 Lab 8: Class complex with GUI........................................................................................ 36 Lab 9: 2D Graphics........................................................................................................... 37 Lab 10: 3D Graphics......................................................................................................... 37 Lab 11 BST: Insertion, Traversal, Search, Depth, Print, Deletion ................................... 39 11.1 Lab Assignment: Insert and traversal of BST...................................................... 40 11.2 Lab Assignment Depth function of BST ............................................................ 40 11.3 Lab Assignment. Print a BST sideway ................................................................. 41 11.4 Lab Assignment (hard) Delete a node programmatically .................................... 41 Lab 12 Stacks and RPN .................................................................................................... 50 Lab 13 Compiler Application (RPN)................................................................................ 50 Lab 14 Database (JDBC) .................................................................................................. 56 Lab 14.1 A Java database application to access Microsoft Access database and display ....................................................................................................................................... 56 Lab 14.2 Database Query.............................................................................................. 59 Lab 15: Java Time............................................................................................................. 59 Lab 16 Cryptography: Encryption and Decryption (Caesar Cipher and RSA) ................ 60 16.1 Lab Assignment: Caesar Cipher ........................................................................... 62 16.2.1 Lab Assignment: Factorization of an integer n into p q................................. 64 16.2.2 Lab Assignment. RSA encryption ................................................................ 65 16.2.3 Lab Assignment: Decipher RSA.................................................................... 65 Lab 17: Java Security Extensions ..................................................................................... 67 Lab 18: Java Networking .................................................................................................. 67 Lab 19: Java email ............................................................................................................ 68 Lab Assignment 19.1 Java email .................................................................................. 73 Lab 20: Java Servlets ........................................................................................................ 74 Basic Ideas of J2ME ......................................................................................................... 75 Java Wireless Toolkit (KTool)...................................................................................... 75

Installation of KToolBar in C drive .......................................................................... 75 Start KToolBar:......................................................................................................... 75 Run KToolbar in H drive or via network .................................................................. 76 Palm OS Emulator (POSE)........................................................................................... 82 Lab 21 Hello World In J2ME ........................................................................................... 88 Lab 21.1 Run Hello World in Color Cellular Phone Emulator..................................... 88 Lab 21.2 Run Hello World in Palm OS emulator......................................................... 88 Lab 22: Stock Quotes ........................................................................................................ 88 Lab 23: J2ME Games........................................................................................................ 88 Appendix:.......................................................................................................................... 89 Appendix A: Using JDK ............................................................................................... 89 Appendix B: Using IDE Eclipse ................................................................................... 92

Preface:
J2SE, J2ME and Java extensions.

Part I. Basic Java Lab 1: Hello World Lab 2: Exponential function Lab 3: Class complex Lab 4: Using Eclipse Debugger Lab 5: Compute n factorial and big factorials Lab 6: Animation Lab 7: GUI: 8 puzzle Lab 8: Class complex with GUI Lab 9: 2D Graphics Lab 10: 3D Graphics Part II. Advanced Java Lab 11: BST (Binary Search Tree) Lab 12: Stacks and RPN Lab 13: Compiler application Lab 14: Database (JDBC) Lab 15: Multi- threading Lab 16: Cryptography: RSA, Caesar Lab 17: Java Security Extensions Lab 18: Java Networking Lab 19: Java Email Lab 20: Java Servlet Part III. J2ME (wireless and embedded) Basic Ideas of J2ME Lab 21: Hello World in J2ME Lab 22: Stock Quotes Lab 23: J2ME Games

Lab 1 Hello World


Lab Objectives: After this lab, the students should be able to ? ? ? ? ? ? ? ? Use basic Java tools in JDK for compilation and running. Start JDK Write a simple Java application Modify a simple Java application Write a simple Java applet Run Java applications in JDK Run Java applets in JDK Start the eclipse IDE for Java programs development

Background: Java is an object oriented high level computer programming language evolved from C++. A programming language can not be learned by just studying the programming books and instructor instructions with programming examples. Like swimming and driving, handson experience is necessary to really grasp the language skills. The first milestone of any programming language probably is still the classic way suggested by Kernighan and Thompson from their approach to C language: write a very simple Hello World application in this language and compile (and link) and run. After seeing / making the first program run, the students / readers will know all the nitty- gritty to compile and run. The syntax of the first program can be learned after the first program runs. More about the syntaxes can be learned by trying minor variations which compile as well minor variations which do not compile. The following is the first Java file you will try. Code of HelloWorld.java public class HelloWorld { // main method begins execution of Java application public static void main( String args[] ) { System.out.println( "Hello World!" ); } // end method main } // end class HelloWorld

Note: This same program can be written in ANSI C in a very simple way: Code of HelloWorld.cpp #include <iostream> using namespace std; int main ( ) { cout << Hello World!\n; return 0; } If you do this in BASIC languages, it is even shorter 100 PRINT HELLO WORLD Pre-lab: 1. Type the above code of HelloWorld.java (or get from soft copy) and save the file as HelloWorld.java. Dont worry about typos since they will be cleared later when you learn more about the Java language and know what the compiler errors are. 2. Run HelloWorld.cpp. 3. Compare the difference of HelloWorld.java and HelloWorld.cpp. 4. Study appendix A to start JDK and type java command. 5. Study appendix A to start eclipse.

Labs

1.1 Lab Assignment Hello World application in JDK


Step 1. Put the file HelloWorld.java in a folder that you want to compile and run. Step 2. Start console window and navigate to the folder with the file HelloWorld.java Step 3. Type command javac HelloWorld.java (javac is the program for Java compilation). Step 4. If this file compiles, you should see no message and the prompt again. Step 5. Type DOS command dir to list the files in the folder. Step 6. You should see a new file HelloWorld.class (you can tell the file is new by the timestamp of HelloWorld.class file. Step 7. Type command java HelloWorld (note the command name is java, not javac; also you typed the class name HelloWorld but not the whole class name with extension HelloWorld.class) Step 8. If everything goes smoothly, you should see the message Hello World in the console window.

1.2 Lab Assignment Hello World Application Variations.


Step 1. Edit the message Hello World to any message of your own (for example, My First Java Program. You can use Notepad or Windows DOS edit command to make and save the changes. Step 2. Compile this changed java file with javac command. Use time command of DOS to note the time this java file is created (should be later than the one in Lab 1.1.). Step 3. Run the new java file. Which command will you use? Step 4. Edit the file to introduce a syntax error: For example change System.out.println (Hello World); to System.ot.println (Hello World); // type ot for out or to System.out.println (hello World); // miss the closing double quote Step 5. Recompile with javac command. What do you observe?

1.3 Hello World Application in IDE eclipse


Step 1. Start eclipse. Step 2. Create a project HelloWorld Step 3. Create a new class HelloWorld in this project Step 4. Type the code of HelloWorld shown above. Step 5. Run this project by clicking Run As => Java Application Step 6. Show the output in the eclipse output window Step 7. Capture the eclipse screen or the output window

1.4 Hello World Applet in JDK


Step 1. Modify the code of HelloWorld Applet.java as below import javax.swing.JApplet; // add a line to import javax.swing.JApplet public class HelloWorld Applet extends JApplet // modify the class line to add extend JApplet { // main method begins execution of Java application public static void main( String args[] ) { System.out.println( "Hello World!" ); } // end method main

} // end class HelloWorld Applet Step 2. Create an HTML file HelloWorld.html as follows (note the name of the HTML file is the same as the java Applet class)
<html> <applet code = "HelloWorldApplet.class" width = "275" height = "110"> </applet> </html>

Step 3. Save the html file in the same folder as HelloWorldApplet.java file Step 4. Use javac to compile HelloWorldApplet.java (the same as step 3 of Lab 1.1) Step 5. Use appletviewer command to view the applet (you do not use the java command as in step

1.5 Hello World Applet in eclipse

Lab 2 Control Structure: Exponential Function


Lab Objectives:

After this lab, the students should be able to: ? ? Explain the concepts of the math concept infinite serie s. Write program to compute the sum of an infinite series.

Background:
Exponential Function

Exponential function or exp (x) = ex is a mathematical function learned in calculus. ex can be represented as a power series ex = 1 + x + x2 / 2! + x3 / 3! + + xn / n! + , or ? xn symbolically as ? . Here n! (n factorial) is n (n-1) (n-2) 3. 2. 1 (and e = 2.7128..). n ?0 n! It is possible to write a computer program to compute ex using for loop. Note that this function can not be computed by the fo llowing pseudocode: double sum = 0.0; for (int j = 0; j <= ? ; j++) sum += (xj / j!); // the j-th term xj / j! can be computed Note that the j-th term xj / j! can be computed, but the concept or symbol of infinity ? can not be modeled in programming language however. Wrong Approach to compute e (= 2.7128..) or ex in general. When x = 1, the power series ex becomes e. Since ? can not be coded, a natural way is thinking of replacing the for loop for (int j = 0; j <= ? ; j++) by the finite for loop for (int j = 0; j <= N; j ++) for some integer N big enough. What would be the N for computing e? Some picked N = 10, which may be good enough for e (the computed result is ). But what about N for x = 2 (e2), x = 3 (e3), x = 2.5 (e 2.5)? For different x, it seems that different N may be needed (note you can not use pow (e, x) with e = 2.718 to compute ex since pow (a, x) = ax = e x ln a is based on exp function itself). Right Approach to compute e.

From calculus, the power series expansion (Taylor or McLaurin series expansion) n xi satisfies the property f(x) = ? f ( i) ( 0) + error term with | error term | < f(n)(0) xn / n! = i! i? 0 absolute value of (xn / n !), we can compute ex with tolerable error as long as the n-th term is small enough since it means the error is negligible. A possible small number is epsilon = 10 -7 for example. Pre-lab

1. Review Ma114 on how exponential function is represented as a power series. 2. Answer this question: There are infinitely many terms in a power series but in programming language (and algorithms), you can only compute finite number of steps. How can a computer program compute an infinite series then? (hint: use the concept of approximation). 3. Review the for loop concept you learned in C++ language. In particular, how do you stop a for loop?

Labs:

2.1 Lab Assignment: Exponential Function


Step 1. Create an eclipse project Step 2. Type and enhance the following (pseudo) code template to compute ex . double sum = 1.0 double term = 1.0; // initialize the zero-th term 1.0 For (int j = 1; absolute value of error < tolerance; j ++) { term *= x / (double) j; // Compute j-th term xj / j! as the product // of j-1 st term * x / j; // This means xj / j ! = x j-1 / (j-1)! * x / j sum += term ; // } Step 3. Run this program with the different values of x. Step 4. Explain why the j-th term is computed as term *= x / (double) j, not the straightforward term *= j / x (hint: what if x is an integer?).

Lab 3 Complex Numbers


Lab Objectives: After this lab, the students should be able to ? ? ? Explain the complex numbers and the arithmetic of complex numbers. Make user defined type (class) complex with the associated operations. Perform complex arithmetic programmatically

Background: You have learned the concept of class and object. You have also learned the concept of complex number. A complex number c = a + bj consists of two parts, the real part a and the imaginary part bj, where j2 = -1, with j the square root of -1. We can perform arithmetic operations (+, -, *, /, or addition, subtraction, multiplication, and division) on complex numbers: +: (a1 + b1j) + (a2 + b2j) = (a1 + a2) + (b1 + b2)j -: (a1 + b1j) (a2 + b2j) = (a1 a2) + (b1 b2j) *: (a1 + b1j) * (a2 + b2j) = (a1a2 b1b2) + (a1b2 + a2b1) j /: (a1+b1j) / (a2 + b2j) = (a1 + b1j) * (a2 b2j) / (a22 + b22 ) = [(a1a2 + b1b2) + (a2b1 a1b2)j] / (a22 + b22 ) Class complex is usually given as the first programming exercise in class since the concept of complex numbers is easy to understand and it is easy to define the attributes (variables or data) and the methods. A complex number c of the form a + bj can also be expressed in polar form rej ? with r =

a 2 ? b 2 as the magnitude or the value of c, and argument or angle ? as arctan (b/a) (arc tangent of b / a).
Pre-labs : 1. Review the concepts of complex numbers. 2. Write down the formulas of computing the product of two complex numbers. 3. Compute manually the sum, difference, product, and quotient of these complex numbers c1 = 1 + j, c2 = 1 j.

Labs:

3.1 Lab Assignment Class Complex


Step 1. Create an eclipse project (called complex). Step 2. Type in the following code for class complex in Java (the code is different from if you use C++ language where you need .h and .cpp) public class complex { private double rP; private double iP; complex () { // constructor rP = 0.0; iP = 0.0; } complex (double r, double i) { rP = r; iP = i; } public void copy (complex c) { rP = c.rP; iP = c.iP; } public void add (complex c) { rP += c.rP; iP += c.iP; } public void add (complex c, complex d){ rP = c.rP + d.rP; iP = c.iP + d.iP; } public void mul (complex c, complex d){ // Note it is necessary to compute the product // using a new variable c3 for the first variable c // and this may be the same variable and if so,

// the computed rP will change the vlaue of c.rP in // computing iP. // complex c3 = new complex (); c3.rP = c.rP * d.rP - c.iP * d.iP; c3.iP = c.rP * d.iP + c.iP * d.rP; this.copy(c3); } public complex addthree (complex c, complex d){ complex e = new complex (); e.rP = c.rP + d.rP; e.iP = c.iP + d.iP; return e; } public void print () { System.out.println ("(" + rP + ", " + iP + ")"); } public static void main(String[] args) { complex c = new complex (1.0, 1); complex d = new complex (1, -1);

} } Step 3. Build and run this project. Will anything be printed? Why? Step 4. Enhance and complete the main method. In particular add instructions to print c and d (for example, c.print ( );). Step 5. Test that the add and mul methods work (print c + d and c * d).

Lab 4 Using Eclipse Debugger


Lab Objectives: After this lab, the students should be able to: ? ? ? Explain the concept of debugging Explain the significance of debugging Use eclipse debugger to locate the problems of the program

Background: Computer programs generally do not work correctly in the first few attempts. Apart from the compiler errors for the wrong syntaxes, link errors for the undefined methods, and run time exceptions due to null pointers, IO exceptions etc., there is a type of serious errors called logic errors or software bugs that the tools in general can not catch and the so called debugger needs to be employed. If in lab 3 on class complex above, we use a method wrongmul with the code as below (in my ECE429 class, many students coded this way). Note this code is similar the case when we code the sum of two complex numbers (rP += c.RP; iP += c.iP;). public void wrongmul (complex c, complex d){ // wrong ways of computing products // rP = c.rP * d.rP - c.iP * d.iP; iP = c.rP * d.iP + c.iP * d.rP; } If we have c = 1 + j and d = 1 j, we know the product is (1+ j) * (1 j) = 2, but the output corresponding to the code in the main method as below: complex c = new complex (1.0, 1); complex d = new complex (1, -1); System.out.print ("Complex number c: "); c.print(); System.out.print ("Complex number d: "); d.print(); System.out.println ("Mul c and d by wrong method"); c.wrongmul(c,d); c.print();

generates the wrong output as follows where the product is computed as 2 j.


Complex number c: (1.0, 1.0) Complex number d: (1.0, -1.0) Mul c and d by wrong method (2.0, -1.0)

A general method of checking where the error happens is by adding print outs of the intermediate results with System.out.println instructions). That method will be costly if a lot of intermediate results are produced and also it causes the maintenance problem of removing such code later on when the program is debugged. Run Debugger in Eclipse Below we show the steps of how to use the debugger in eclipse. The basic concept is similar to using debugger in C++: you need to know ? ? ? ? ? ? Set / clear breakpoint Start the debugger Stop the debugger Step through Step into Display the variables in debugger

Here a breakpoint is a line of code where the debugger will pause for you to look at the values of variables. If the values are wrong, then it is possibly caused by a buggy instruction. Set / clear breakpoint: As shown in Figure 4-1, in eclipse (3.0 and later), move the mouse the line you want to set (or clear) break point, click Run => Toggle Line Breakpoint.

Figure 4-1 Toggle Breakpoint

Figure 4-2. A blue dot .? appears in the line rP = c.rP * d.rP - c.iP * d.iP;

Figure 4-3. Debug As .. Java Application Start the debugger: after setting the break point, you can start the debugger by clicking Run => Debug As => Java Application as shown in Figure 4-3. A dialog box as in Figure 4-4 pops up asking you to confirm switching from Java perspective to Debug perspective.

Figure 4-4.

Figure 4-5. Debugger pausing at the breakpoint

Figure 4-6. Display variables in debugger.

As shown in Figure 4-5, the display switches from the normal Java perspective of displaying the package Explorer of all the projects and the current code and output to the Debug perspective. The breakpoint instruction is highlighted with a blue arrow in the beginning. In the left middle window. You can display the variable values in the upper right corner. Doubly click the first item called this = complex) in the upper right window called Variables and also doubly click the second item called c = complex, you can see after orange squares, iP = 0.0; rP = 0.0 for the variable this, and iP = 1.0; and rP = 1.0 for the variable c. These values are correct since c is initialized to 1 + i (from the Java instruction Complex
number c: (1.0, 1.0);), and the variable this is normally set to 0 + 0i.

Figure 4-7. Menu in Debug perspective showing the keys. By clicking Run, you can pop down a menu showing the function keys to control the debugger (the third icon as orange square is Terminate used to terminate debugger): F6 to step over, F5 to step into).

If the current instruction is an instruction, then F5 or F6 either will move to the next instruction. However if the current instruction is a method call / function call, hitting F5 will step into that method call instead of moving to the next instruction.

Figure 4-8. rP calculated correctly as 2.0

Figure 4-9. iP calculated incorrectly as -1.0 (should be 0.0). At this moment, hitting F6 to move to the next instruction iP = c.rP * d.iP + c.iP * d.rP;, we get rP = 2.0 for both this and c, which is correct. Actually this and c have identical values, both have rP = 2.0 and iP = 1.0, why? (please answer this in pre- lab). Hitting F6 again, you will se the new values of this and c are: rP = 2.0 (correct) and iP = 1.0., which is incorrect! At this moment, you can probably see what caused the problem.

The original value of rP (1.0 since c = 1 + i) should be used to calculate P instead of the newly calculated rP (2.0). If you understand why, we have used the debugger to find that the offending code (the second line). For code style and software engineering purpose, we should try to fix both lines. The fix is done as in the mul method in lab 3 (not the wrongmul method here) where this is first copied to a new complex variable c3 and c3 computed using c and d and finally c3 copied back to this. Stop Debugger: To stop the debugger, click Run => Terminate. You will see debugger perspective without any variables displayed. Now you can resume by clicking Run =? Debug Last Launched or you can go back to Java perspective to fix the code (and then rebuild to see if that works correctly).

Figure 4-10. Open the Java perspective to the normal mode of editing and building

Pre-lab:

1. Follow the steps in the background section, set break pint and start the debugger (it does not have to be complex.java). 2. Answer this question: in the backgrounds section, there is the question why the variable this and c have the same values?.

3. Lab:

Lab 4.1 Using Debugger to Locate a Problem in class Complexs multiply method

Lab 5: Compute n factorial and big factorials


Lab Objectives: After this lab, the students should be able to ? Explain what overflow can cause wrong outputs in calculating big integers in Java using the intrinsic int type ? Explain what class BigInteger is and if BigInteger class can express integers of 10 digits that int type can not display correctly ? Compute a big factorial such as 50! ? Compute a big power such as 2100 ? Compute a prime number of 10 digits or longer (that int type can not do). Background: Factorial (n! = n (n-1)(n-2) 3.2. 1) is a popular function using the for loop in the introductory programming class. It is easy to find 3! = 3 . 2. 1 = 6, 5! = 5 .4 . 3. 2. 1 = 120 by hand and also to write simple for loop code snippet like below to compute such as: int n = 5; int factorial = 1; for (int i = 1; <= n; I ++) factorial *= I; System.out.println (n + ! is + factorial); Figure 5-1. Simple for loop to compute n! Here the value of n can be hard coded or can be input from keyboard (using System.in) or using a dialog box input like JOptionPane. However, if you set n to 100, you will see it displays 100! is 0. If you set n to 12, you can see 12 ! is 479001600 that you can verify is correct. If you set n to 15, youll see some funny result: 15 ! is 2004310016; if you set n to 17, youll see something else funny: 17 ! is -288522240. More funny results here: 32 ! is -2147483648 33 ! is -2147483648, 34 ! is 0 (you can write an outer loop around the code snippet above and print the result of n! for n =1 to 100). Whats funny is that, n! is the product of positive integers, hence it must be positive, so it makes no sense that 17! Is computed negative, and 34! and 100! computed to be 0.

We see 15! Is positive. Does that mean it is computed correctly? No! Do you know why? 10! is 3628800. Any n! with n>= 10 is equal to n (n-1) (n-2) 11 * (10!), hence n! is a multiple of 10! and it must end in two or more zeroes, so ending in 16 is meaningless. The reason for this is: we use int type to compute n! and int type is a signed type with 4 bytes, which means the largest integer it can represent is 231 -1 or around 2G, 2 billions, or 9 digits, etc. In Java, there is a way to overcome this overflow problem by using the BigInteger class in java.math package. BigInteger virtually has unlimited number of digits, for example, you can print out 100! which is more than 2000 digits long. You can get more information on class BigInteger by the following web link or by searching keyword class BigInteger in Java. http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigInteger.html In C++ language, there is no counterpart (Int64 supports 8 bytes or 63 bits, about 19 digits). A programmer can develop c user defined class to simulate that such as Huge Integer class (see my C / C++ lab manual, lab 19, Huge Integer). The following is a piece of code that computes 100! import java.math.*; public class BigFact { public static void main(String[] args) { BigInteger total = BigInteger.valueOf(1); for (int i = 2; i<= 1000; i++) for (int i = 2; i<= 5; i++) total = total.multiply(BigInteger.valueOf(i)); System.out.println(total.toString());

//

} } Figure 5-2. Code BigFact.java to compute 100! The output (100!) is as follows:
40238726007709377354370243392300398571937486421071463254379991042993851 23986290205920442084869694048004799886101971960586316668729948085589013 23829669944590997424504087073759918823627727188732519779505950995276120 87497546249704360141827809464649629105639388743788648733711918104582578 36478499770124766328898359557354325131853239584630755574091142624174743 49347553428646576611667797396668820291207379143853719588249808126867838

37455973174613608537953452422158659320192809087829730843139284440328123 15586110369768013573042161687476096758713483120254785893207671691324484 26236131412508780208000261683151027341827977704784635868170164365024153 69139828126481021309276124489635992870511496497541990934222156683257208 08213331861168115536158365469840467089756029009505376164758477284218896 79646244945160765353408198901385442487984959953319101723355556602139450 39973628075013783761530712776192684903435262520001588853514733161170210 39681759215109077880193931781141945452572238655414610628921879602238389 71476088506276862967146674697562911234082439208160153780889893964518263 24367161676217916890977991190375403127462228998800519544441428201218736 17459926429565817466283029555702990243241531816172104658320367869061172 60158783520751516284225540265170483304226143974286933061690897968482590 12545832716822645806652676995865268227280707578139185817888965220816434 83448259932660433676601769996128318607883861502794659551311565520360939 88180612138558600301435694527224206344631797460594682573103790084024432 43846565724501440282188525247093519062092902313649327349756551395872055 96542287497740114133469627154228458623773875382304838656889764619273838 14900140767310446640259899490222221765904339901886018566526485061799702 35619389701786004081188972991831102117122984590164192106888438712185564 61249607987229085192968193723886426148396573822911231250241866493531439 70137428531926649875337218940694281434118520158014123344828015051399694 29015348307764456909907315243327828826986460278986432113908350621709500 25973898635542771967428222487575867657523442202075736305694988250879689 28162753848863396909959826280956121450994871701244516461260379029309120 88908694202851064018215439945715680594187274899809425474217358240106367 74045957417851608292301353580818400969963725242305608559037006242712434 16909004153690105933983835777939410970027753472000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000000000000 000000000000

Figuer 5-3 100! Computed by BigInteger class. You can copy the above number in a Word document and use Word Count utility to find how many characters it has (hence how many digits it has). It is actually possible to just write a small Java code snippet to read that as a string, and count the length of string. Lets study the code a little bit. To set a BigInteger variable total to 1, you can not write BigInteger total = 1; like you did for the int type int small = 1; Instead you have to write BigInteger total = BigInteger.valueOf(1); Here valueOf is a method of the class BigInteger. Also, you can not write factorial *= i; to compute factorial = factorial * I; instead you have to use the class method multiply, hence total = total.multiply(i); Pre-lab:

1. Enhance the code snippet in Figure 5-1 to compute and display n! for n from 1 to 20. From the output, show where (at which n) the overflow occurs (weknow 12! Is fine and 15! is bad. Does the problem happen at n = 13, 14, or 15?) 2. Study BigIteger class. 3. Write a couple of Java code lines to print out the number of digits for 100!

Lab: Step 1. Type and run the BigFact.java in Figure 5-2. Do you get the > 2000 digits output as in Figure 5-3? Step 2. Change ns value to the smaller 5 or 10 to verify that BigIteger class computes 5! as 120 and 10! as 3628800. Step 3. Change n to 15 to compute 15!. What do you get? Step 4. Why can you say the value of 15! Computed by BigFact.java in Figure 5-2 is correct while the value calculated by code snippet similar to Figure5-1 is wrong? Step 5. Now consider computing some big powers like 210 , 220 , 230 , 250 , and 2100 using int type and BigInteger type. Step 6. Compute a prime number of 3 digits (you can use int type, but you are encouraged to use BigInteger type). Step 7. Compute a prime number of 7 digits, then 10 digits, then 20 digits using the same java code you developed in step 6. Can you time this?

Lab 6: Animation
Lab Objectives: After this lab, the students should be able to: ? ? ? Explain how a simple animation can be done by erasing old image and creating new image at a nearby location Run a simple animation program Modify slightly a working animation program

Background:

Lab import java.awt.*; import java.applet.Applet; public class Ball extends Applet { private int x = 7, xChange = 7; private int y = 2, yChange = 2; private int diameter = 10; private int rectLeftX = 0, rectRightX = 100;

private int rectTopY = 0, rectBottomY = 100; public void paint (Graphics g) { g.drawRect(rectLeftX, rectTopY, rectRightX - rectLeftX, rectBottomY - rectTopY); for (int n = 1; n< 100; n++) { Color backgroundColour = getBackground(); g.setColor(backgroundColour); g.fillOval(x, y, diameter, diameter); if (x + xChange <= rectLeftX) xChange = -xChange; if(x+xChange + diameter >= rectRightX) xChange = -xChange; if (y+yChange <= rectTopY) yChange = -yChange; if(y + yChange + diameter >= rectBottomY) yChange = -yChange; x = x + xChange; y = y + yChange; g.setColor(Color.red); g.fillOval (x, y, diameter, diameter); try { Thread.sleep(200); } catch (InterruptedException e) { g.drawString("sleep exception", 20, 20); } } } } Step 1. Create a Java project using eclipse. Step 2. Type the code above, save in a file and then import this file. Step 3. Run this Java program as an Java applet in eclipse. Step 4. Run this Java program in the console window as an applet (using appletviewer). Step 5. Enhance this program.

Lab 7 GUI: 8 puzzles


Lab Objectives: After this lab, the students should be able to ? ? ? ? Explain what GUI (Graphical User Interface) is Explain the significance of GUI Explain at least 5 basic GUI components (such as labels, text fields, buttons, etc.) Write the code snippets of simple GUI components

Background: GUI is the graphical user interface component of a program. Based on the user interfaces, a Java program can be classified into ? ? ? No user interfaces (no user input or no user output) Having user interfaces but no graphical user interfaces Having Graphical User Interfaces

A Java program may have no user input such as a Java program to compute n! or prime numbers less than 100. A Java program without user output such as System.out.println with monitor messages is virtually useless since the user would not know what has been computed by the Java program (unless the user uses Debugger to check the values computed). A Java program with only user interfaces but no graphical user interfaces takes inputs from keyboard and displays outputs to the monitor. These programs put emphasis more on the logic of the program. A Java program with GUI is more user friendly to the users in that the users do not usually have to remember what to type in (inputs are usually a button click, a radio button or a checkbox to click, or one item to select from a drop down list). There are still cases where the user has to type in data such as the text field (like a blank to fill in) or a text area. The GUI outputs are usually a label or some message coming in a box seamlessly integrated with the graphic user inputs as well. Every GUI component is a resource to be managed by the program whatever the programming language is. Some IDEs provide tools like a toolbox where the users can use mouse to drag a GUI component into the panel or the form, rename the GUI, modify the properties of the GUI etc. Such tools are handy but are not a part of the programming language.

References: All the GUI components in Java have an associated Java class and all the methods associated to set or get the attributes of the GUI component.

Label is a GUI component that displays text (or image). Labels can not be clicked or filled in by the user at run time. In the following screen capture of the GUI in Word to change font properties, the texts are labels; for example Font:, Font color: Effects etc. The labels are usually used to enhance or display information for the users

Labels are programmed as JLabel in Java language. To display the texts Fonts, Font colors, etc., the user needs to code as a minimum the following snippet: import javax.swing.JLabel; // A line before main method to include the package JLabel JLabel labela, labelb; // A line inside the program to declare two labels as JLabel class

labela = new JLabel (Fonts); // Lines to initialize the texts of the labels labelb = new JLabel (Font colors); add (Labela); // Lines to add the GUI component labels to the panel / frame add (labelb); There are other lines the user has to add such as Changing the line class MyProgram to Class MyProgram extends JFrame. Though the user can not interact with the labels directly at run time, the user can use other GUI components such as buttons to change the labels during run time.

Buttons Button is a GUI component that the user can click to have some actions. The GUI components OK , Cancel, and Default.. are all buttons. Buttons are represented by JButton class in the Java language. Button texts can be initialized like button1 = new JButton (OK); However, the texts of a button can be changed at run time after the user clicks the button (the button click starts a method called ActionListener which is processed at run time). With the button click the user can change the text of the button clicked, or another button not clicked, or the texts of labels, or other GUI components with set methods. The button can also be moved by the button click (see labs after). Pre-lab Labs:

Lab 7.1 A moving button Lab 7.2 Write the GUI program for 8 puzzles movement

Figure 7-1 original 5 puzzles

Figure 7-2 5 puzzles with a couple moved.

Code modified from Deitels GridLayoutFrame.java to display 5 buttons that when clicked will move

// Fig. 11.43: GridLayoutFrame.java // Demonstrating GridLayout. import java.awt.GridLayout; import java.awt.Container; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JFrame; import javax.swing.JButton; public class GridLayoutFrame extends JFrame implements ActionListener { private JButton buttons[]; // array of buttons private final String names[] = {"0", "1", "2", "3", "4", ""}; private boolean toggle = true; // toggle between two layouts private Container container; // frame container private GridLayout gridLayout1; // first gridlayout private GridLayout gridLayout2; // second gridlayout int buttonpos [][] = {{0, 1, 2}, {3, 4, 5}};

// no-argument constructor public GridLayoutFrame() { super( "GridLayout Demo" ); gridLayout1 = new GridLayout( 2, 3, 5, 5 ); // 2 by 3; gaps of 5 gridLayout2 = new GridLayout( 3, 2 ); // 3 by 2; no gaps

container = getContentPane(); // get content pane setLayout( gridLayout1 ); // set JFrame layout buttons = new JButton[ names.length ]; // create array of JButtons for ( int count = 0; count < names.length; count++ ) { buttons[ count ] = new JButton( names[ count ] ); buttons[ count ].addActionListener( this ); // register listener add( buttons[ count ] ); // add button to JFrame } // end for } // end GridLayoutFrame constructor // handle button events by toggling between layouts /* public void actionPerformed( ActionEvent event ) { if ( toggle ) container.setLayout( gridLayout2 ); // set layout to second else container.setLayout( gridLayout1 ); // set layout to first toggle = !toggle; // set toggle to opposite value container.validate(); // re-layout container } // end method actionPerformed */ public void actionPerformed( ActionEvent event ) { String x; int i = 0, j = 0, ix; int hi, hj, mi, mj; // matrix index of hole and button int x5, y5, xm, ym; x = event.getActionCommand(); System.out.println (x + " clicked"); ix = Integer.parseInt (x); if (ix == 6) return; // Find where the hole is outer: for (i = 0; i < 2; i ++) for (j = 0; j < 3; j ++) {

if (buttonpos [i][j] == 5) break outer; }

hi = i; hj = j; System.out.println ("Before the click"); System.out.println ("The hole is located at (" + hi + ", " + hj + ")"); outer2: for (i = 0; i < 2; i ++) for (j = 0; j < 3; j ++) { if (buttonpos [i][j] == ix) break outer2; } mi = i; mj = j; System.out.println ("The button is located at (" + mi + ", " + mj + ")"); x5 = buttons[5].getX(); y5 = buttons[5].getY(); System.out.println("x5 is " + x5); System.out.println ("y5 is " + y5); // xm = buttons[mi * 3 + mj].getX(); // ym = buttons[mi * 3 + mj].getY(); xm = buttons[buttonpos[mi][mj]].getX(); ym = buttons[buttonpos[mi][mj]].getY(); System.out.println("xm is " + xm); System.out.println ("ym is " + ym); System.out.println ("Button pos array is"); for (int k = 0; k < 2; k ++) for (int k1 = 0; k1 < 3; k1++) System.out.print (buttonpos [k][k1] + " "); System.out.println (""); if ((hi == mi && hj == mj + 1) || // hole as the immediate neighbor of button) (hi == mi && hj == mj - 1) ||

(hi == mi + 1 && hj == mj) || (hi == mi - 1 && hj == mj)) { // // buttonpos [mi][mj] = 5; buttonpos [hi][hj] = ix; // switch button and hole buttons[5].setLocation (buttons[buttonpos[mi][mj]].getLocation()); buttons[5].setY(ym); buttons[buttonpos[mi][mj]].setLocation(x5, y5); buttonpos [mi][mj] = 5; buttonpos [hi][hj] = ix; System.out.println ("After the click"); System.out.println ("The new button sequence is"); for (int k2 = 0; k2 < 2; k2 ++) for (int k3 = 0; k3 < 3; k3++) System.out.print (buttonpos [k2][k3] + " "); System.out.println (""); } // end of if // buttons[4].setLocation (buttons[5].getLocation()); } } // end class GridLayoutFrame /*********************************************************************** *** * (C) Copyright 1992-2005 by Deitel & Associates, Inc. and * * Pearson Education, Inc. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * ************************************************************************ */

//

Lab 8: Class complex with GUI

The first screen shows the screen without inputs and the second one shows inputting 1 + i (1 in the first real and 1 in the first imaginary) and 1 i (with 1 and -1 in the textfields) with the sum (2.0, 0.0) standing for 2 + 0i, the sum of 1 + I and 1 i. (a) Enhance the code provided to add the GUIs for difference, product, and quotient. (b) Show the output of your enhanced code with three new buttons for - * and / operations. (c) Test your code by the input pairs 1 + i and 1 i and also another input pairs 2 + i and 3 i. Provide one more pair of your own inputs. All inputs must be from keyboard. Show the screen captures of inputting these 3 pairs and the outputs with 4 different methods. Attach the code.

Lab 9: 2D Graphics Lab 10: 3D Graphics

Figure 101- : j3daudio.jar, j3dcore.jar, j3dutils.jar At the location: C:\Program Files\Java \jdk1.5.0_02\jre\lib\ext

Lab 11 BST: Insertion, Traversal, Search, Depth, Print, Deletion


Lab Objectives: After this lab, the students should be able to ? ? ? ? ? ? ? Explain the concepts of the data structure binary search tree (BST). Explain how a node is inserted into a BST. Explain the concepts of pre-order traversal, in-order traversal, and post-order traversal. Write programs to compute the depth of a BST. Write programs to print a BST. Explain the concepts of removing a node from a BST

Backgrounds: A tree is a graph without cycles. A tree is also a two dimensional data structure. A binary tree with root r starts from the node r, and every node has at most two downlinks, one to the left for the left child, and another one to the right for the right child. All the nodes down to the left of a given node form the left sub-tree of the node, and all the nodes down to the right of the node form the right sub-tree. A node without any child (at the bottom) is called a leaf. BST property: A binary search tree (BST) is a binary tree with an order < defined between nodes so that all the nodes n in the left sub-tree of a given node k satisfy n < k and the all the nodes in the right sub-tree of a given node k satisfy n > k. Insert Operation: Given a BST, a new node n is inserted so that the BST property is maintained. This can be explained in a recursive way, node n is first compared with root r and then later with another node k (k = r at first), if n is < k, then n is either inserted as a left child of k if there is no left child of k or n is then compared with the left child of k; and if n > k, then n is inserted as the right child of k if there is none or n is then compared recursively with the right child of k. The computer program is then written this way. Build a BST: Given an input sequence, a BST is built by putting the first entry as the root, and all the other entries are inserted by Traversal: Delete Operation: when removing a node from the BST, the important thing is to make sure the BST property is maintained after the removal of the node.

The followings are the considerations necessary to consider when deleting a node (see Deitel Visual C++.NET book p. 1168). If the node to be deleted is a leaf node, the node is deleted and the reference to the parent node is set to null. If the node to be deleted is a node with one child, the reference in the parent node is set to refer to the child node, and then the node is deleted. The case remaining is hard: deleting a node n with two children. A node in one of the sub-trees must take over the place. The replacement node is in general not one of the two children nodes of the node to delete. This replacement node k must be either the largest node in the left subtee (where all nodes have values < the node n to delete) or the smallest node in the right subtee (where all nodes have values > the node n to delete). When n is replaced by k, it is clear that all the other nodes in the left subtree are < k (since k is either the largest one in the left subtree, or k is the smallest in the right subtree and every node in the right subtree including k is supposed to be bigger than every node in the left subtree). We can also know that k > all the nodes in the right subtree. Hence BST property is preserved if n is replaced by k. There are two issues left now: how to find k, and how to redirect ks children. Find the replacement node k: suppose we are looking for k in the left subtree. This node is the largest in the left subtree. To find this node k, we walk down the left subtree to the right until the current node has no right child (no node bigger than that). Since we walked to the right, this means the nodes are getting bigger and bigger Pre-labs Lab:

11.1 Lab Assignment: Insert and traversal of BST 11.2 Lab Assignment Depth function of BST
(Java code: to be modified to C++) public int depth () { // returns the depth of the tree if (leftNode == null && rightNode == null) return 1; else if (leftNode == null)

return rightNode.depth() + 1; else if (rightNode == null) return leftNode.depth() + 1; else return Math.max(le ftNode.depth(), rightNode.depth()) + 1;

11.3 Lab Assignment. Print a BST sideway


public void inorderPrint() { depth = root.depth(); inorderPrintHelper( root ); } // end method inorderTraversal // recursive method to perform inorder traversal private void inorderPrintHelper( TreeNode node ) { if ( node == null ) return; localdepth ++; inorderPrintHelper( node.rightNode ); // traverse left subtree // System.out.printf( "%d ", node.data ); // output node data

nospaces = 5 * localdepth; // print blank lines and enough number of spaces for (int i = 0; i < nospaces; i ++) System.out.print (" "); System.out.print (node.data); // System.out.print (" depth: " + localdepth // + " spaces " + nospaces); System.out.println (); inorderPrintHelper( node.leftNode ); localdepth --; } // end method inorderHelper // begin postorder traversal // traverse right subtree

11.4 Lab Assignment (hard) Delete a node programmatically


public void delete (int deleteValue) { // delete from left tree

if (deleteValue < data) { if (leftNode != null) { parentNode = this; currentNode = leftNode; // System.out.println ("Before setting, Boolean values are right: " // + right + " left: " + left); left = true; right = false; // // System.out.println ("After setting, Boolean values are right: " + right + " left: " + left); leftNode.delete(deleteValue );

} else System.out.println ("left search failed for " + deleteValue + " with parent " + data); } else if (deleteValue > data) // delete from right tree if (rightNode != null) { System.out.println ("Before: Boolean values are right: " + right + " left: " + left); right = true; left = false; parentNode = this; currentNode = rightNode; // // } else System.out.println ("right search failed for " + deleteValue + " with parent " + data); else // deleteValue = data now // Apply the 5 steps in the algorithm // Find replacement node first { System.out.println ("Found value to delete " + data); // There are 3 cases for the node to delete: // Case 1: node is a leaf node System.out.println ("After: Boolean values are right: " + right + " left: " + left); rightNode.delete(deleteValue);

// //

//

// node is deleted, // reference (left or right // node of the parent node) set to null // Case 2: node has one child, // node is deleted // parent node reference is set to reference // the child of this node // Case 3: node has two children if (parentNode != null) System.out.println ("Parent node of current node is " + currentNode.parentNode.data); else System.out.println("No parent node, this is root"); if (rightNode == null && leftNode == null) // case 1 { // set parent node's reference (could be left or right) // to this node to null currentNode = null; System.out.println ("a leave node deleted"); System.out.println ("Boolean values are right: " // + right + " left: " + left); if (right) parentNode.rightNode = null; else if (left) parentNode.leftNode = null; else // should not come here System.out.println ("Error"); }

else if (rightNode == null || leftNode == null) // exaclty one of leftNode or right node is null // point the parent of the deleting node to // the child directly { if (left){ parentNode.leftNode = currentNode.leftNode; } else if (right){ parentNode.rightNode = currentNode.rightNode; } else // the case of root { System.out.println ("Removing the root");

if (rightNode == null){ System.out.println ("right subtree empty"); currentNode = this; repNode = currentNode.leftNode; // get the left // subtree if (repNode.rightNode != null){ System.out.println ("Nonnull right node for rep"); repright = true; // need to find the parent node of the // replacement node while (repNode.rightNode != null) { repParentNode = repNode; repNode = repNode.rightNode; } // System.out.println ("The rep node data is ") } // end of if if (repParentNode != null) System.out.println ("The replacement parent is " + repParentNode.data); System.out.println ("The replacement node is " + repNode.data); // The case for root, there is no parentNode currentNode.data = repNode.data; if (repright){ // the replacement node has right link // need to set the right link of the parent of // replacement to // the left child of the replacement node repParentNode.rightNode = repNode.leftNode; repright = false; } System.out.println ("Rep node data is " + repNode.data); System.out.println ("Current node data is " +

currentNode.data);

// Set the left link of rep unless I am the left link of // the parent if (repNode.data != currentNode.leftNode.data) { repNode.leftNode = currentNode.leftNode; System.out.println ("set rep left"); } } // end of rightNode == null for the root else // leftNode == null for the root // coding is just the opposite switch left <=> right { System.out.println ("left subtree empty"); currentNode = this; repNode = currentNode.rightNode; // get the left // subtree if (repNode.leftNode != null){ System.out.println ("Nonnull left node for rep"); repright = true; // need to find the parent node of the // replacement node while (repNode.leftNode != null) { repParentNode = repNode; repNode = repNode.leftNode; } // System.out.println ("The rep node data is ") } // end of if if (repParentNode != null) System.out.println ("The replacement parent is " + repParentNode.data); System.out.println ("The replacement node is " +repNode.data); // The case for root, there is no parentNode

currentNode.data = repNode.data;

if (repright){ // the replacement node has right link // need to set the right link of the parent of // replacement to // the left child of the replacement node repParentNode.leftNode = repNode.rightNode; repright = false; } System.out.println ("Rep node data is " + repNode.data); System.out.println ("Current node data is " + currentNode.data);

// Set the left link of rep unless I am the left link of // the parent if (repNode.data != currentNode.rightNode.data) { repNode.rightNode = currentNode.rightNode; System.out.println ("set rep right"); } } } } // end of case 2 else // case 3. The node to be deleted contains two // children. It has to be replaced by a repNode // as the largest node in the left subtree // or the smallest node in the right subtree // The replacement node can have also two // subcases: // case 3.1 replacement node is a leaf node // case 3.2 replacement node has only one child to the left { // Compute the replacement node in the left subtree currentNode = this; repNode = currentNode.leftNode; // get the left subtree

if (repNode.rightNode != null){ System.out.println ("Nonnull right node for rep"); repright = true; // need to find the parent node of the replacement node while (repNode.rightNode != null) { repParentNode = repNode; repNode = repNode.rightNode; } System.out.println ("The rep node data is ")

// } if (repParentNode != null) System.out.println ("The replacement parent is " + repParentNode.data); System.out.println ("The replacement node is " +repNode.data); if (right || left ){ if (right) parentNode.rightNode = repNode; else if (left) parentNode.leftNode = repNode; // common code for either down right or left repNode.rightNode = currentNode.rightNode;

if (repright){ // the replacement node has right link // need to set the right link of the parent of // replacement to // the left child of the replacement node repParentNode.rightNode = repNode.leftNode; repright = false; } System.out.println ("Rep node data is " + repNode.data); System.out.println ("Current node data is " + currentNode.data);

// Set the left link of rep unless I am the left link of the // parent if (repNode.data != currentNode.leftNode.data) { repNode.leftNode = currentNode.leftNode;

System.out.println ("set rep left"); } } else // the case of root { System.out.println ("root to remove"); currentNode = this; repNode = currentNode.leftNode; // get the left subtree if (repNode.rightNode != null){ System.out.println ("Nonnull right node for rep"); repright = true; // need to find the parent node of the replacement // node while (repNode.rightNode != null) { repParentNode = repNode; repNode = repNode.rightNode; } // System.out.println ("The rep node data is ") } // end of if if (repParentNode != null) System.out.println ("The replacement parent is " + repParentNode.data); System.out.println ("The replacement node is " +repNode.data); // The case for root, there is no parentNode

currentNode.data = repNode.data;

if (repright){ // the replacement node has right link // need to set the right link of the parent of // replacement to // the left child of the replacement node repParentNode.rightNode = repNode.leftNode; repright = false; } System.out.println ("Rep node data is " + repNode.data); System.out.println ("Current node data is " +

currentNode.data);

// Set the left link of rep unless I am the left link of the // parent if (repNode.data != currentNode.leftNode.data) { repNode.leftNode = currentNode.leftNode; System.out.println ("set rep left"); } // } } // end of the case of root

} // end case 3 } // end delete = value } // end of method delete

Lab 12 Stacks and RPN Lab 13 Compiler Application (Postfix calculation)


// Fig. 20.11: StackInheritanceTest.java // Class StackInheritanceTest. // import com.deitel.jhtp5.ch20.StackInheritance; // import com.deitel.jhtp5.ch20.EmptyListException; import javax.swing.JOptionPane; public class StackInheritanceTest { public static void main( String args[] ) { StackInheritance stack = new StackInheritance(); // create objects to store in the stack Boolean bool = Boolean.TRUE; Character character = new Character( '$' ); Character clparen = new Character ('('); Integer integer = new Integer( 34567 ); String string = "hello"; // String infix = "(6 + 2) * 5 - 8 / 4";

String infix = JOptionPane.showInputDialog ("Enter infix expression"); // String infix = "6 + 2"; String postfix = ""; char x; int count = 0;

Character ch1 = new Character ('1'); Integer in2 = new Integer (2); Character chp = new Character ('+'); String st1 = new String ("(");

// 1. Push a left parenthesis onto the stack stack.push ("(");

// 2. Append a right parenthesis ')' to the end of infix infix = infix + ")";

//

System.out.println ("Infix is " + infix); // 3. While the stack is nonempty, read infix from left to right (parse) and // 3.1 if the current character in infix is a digit, append it to postfix // 3.2 if the current character in infix is a left parenthesis, push it onto stack // 3.3 If the current character in infix is an operator // Pop operators (if there are any) at the top of the stack // while they have equal or higher precedence than the // current operator, and append the popped operators to postfix // Push the current character in infix onto the stack // 3.4 If the current character in infix is a right parenthesis // Pop the operators from the top of the stack and append them to postfix until // a left parenthesis is at the top of the stack // Pop (and discard) the left parenthesis from the stack

while (!stack.isEmpty()) { // step 3 while nonempty stack // count ++; // System.out.println ("While loop executed " + count + " times"); for (int i = 0; i < infix.length(); i ++){ // step 3 parse x = infix.charAt(i); if (x >= '0' && x <= '9') // digit, 3.1: append to postfix { postfix += " "; postfix += x; } else if (x == '(') // push it onto the stack stack.push ("("); else if (isOperator(x)) // { Object o; char y; String z; o = stack.getHead(); // check the top of stack System.out.println ("Stack top is " + o); z = (String) o; y = z.charAt(0); while (isOperator (y) && precedence (x, y)){ // if stack top of // higher priority

stack.pop(); postfix += " "; postfix += o; System.out.println ("Postfix in while loop is " + postfix); o = stack.getHead(); // check the top of stack z = (String) o; y = z.charAt(0); } // Character clx = new Character (x); String stx; stx = infix.substring(i, i+1); stack.push (stx); } else if (x == ')') { Object top; String ts; char tc; boolean found = false; while (!found){ // Pop the top operators from the stack // and append them to postfix until a '(' top = stack.pop(); ts = (String) top; tc = ts.charAt (0);

if (tc == '(') found = true; else { postfix += " "; postfix += tc; } }

} // end of for loop

} // end of while loop System.out.println ("Postfix is " + postfix); // use push method /* stack.push( bool ); stack.print(); stack.push( character ); stack.print(); stack.push( integer ); stack.print(); stack.push( string ); stack.print();

// remove items from stack try { Object removedObject = null; while ( true ) { removedObject = stack.pop(); // use pop method System.out.println( removedObject.toString() + " popped" ); stack.print(); } } // catch exception if stack is empty when item popped catch ( EmptyListException emptyListException ) { emptyListException.printStackTrace(); } int number = 13; int remainder; Integer rem = new Integer (0); while (number != 0){ remainder = number %2; if (remainder == 1) rem = Integer.valueOf ("1"); else rem = Integer.valueOf ("0");

stack.push(rem); stack.print(); number /= 2;

} */ } // end of main public static boolean isOperator (char x){ // returns if a character is an operator return (x == '+' || x == '-' || x == '*' || x == '/' || x == '^' || x == '%'); } public static boolean precedence (char a, char b){ return ((a == '+' || a == '-' ) && (b != '+' && b != '-') || // "+- " < "*/%^ (a == '*' || a == '/' || a== '%') && b == '^' ); // "*/%" < "^" }

} // end class StackInheritanceTest

/*********************************************************************** *** * (C) Copyright 1992-2003 by Deitel & Associates, Inc. and * * Prentice Hall. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. *

************************************************************************ */

Lab 14 Database (JDBC)


Lab Objectives: After this lab, the students should be able to ? ? ? ? ? Explain the basic concepts of relational databases and DBMS (database managements system). Explain the concepts of tables, fields, and records in databases Design and create a simple database manually in Microsoft Access DBMS Write a Java program to display a table from a database Write a Java program to query a database and

Background: Database is the most organized way of defining and saving data. In relational database, data are saved in table(s) linked by relationships and every table captures a data entity with many records of similar attributes.

Reference: Deitel & Deitel, Java, chapter

Pre-lab: Lab

Lab 14.1 A Java database application to access Microsoft Access database and display
import java.awt.*; import java.sql.*; import javax.swing.*; public class BooksDataBase extends JFrame{ //JDBC driver name and database URL static final String JDBC_DRIVER = "sun.jdbc.odbc.JdbcOdbcDriver"; static final String DATABASE_URL = "jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};DBQ=c:\\Books.mdb";

//declare Connection and Statement for accessing //and querying database private Connection con; private Statement statement; //constructor connects to database, queries database, processes //results and displays results in window public BooksDataBase() { super("Books"); //connect to database Books.mdb and query database try{ //specify location of database on filesystem System.setProperty( "C:\ \Books.mdb","null" ); //load database driver class Class.forName(JDBC_DRIVER); //establish connection to database con = DriverManager.getConnection(DATABASE_URL); //Status Result Set //create statement for querying database statement = con.createStatement(); //query database ResultSet resultSet = statement.executeQuery("SELECT authorid, firstName, lastName FROM Authors"); //process query results StringBuffer results = new StringBuffer(); ResultSetMetaData metaData = resultSet.getMetaData(); int numberOfColumns = metaData.getColumnCount(); for( int i = 1; i <= numberOfColumns;i++) results.append( metaData.getColumnName(i) + "\t"); results.append("\n"); while (resultSet.next()){

for (int i = 1; i <= numberOfColumns; i++) results.append( resultSet.getObject(i) + "\t"); results.append("\n"); } //set up GUI and display window JTextArea textArea = new JTextArea( results.toString() ); Container container = getContentPane(); container.add( new JScrollPane( textArea )); setSize( 350, 300 ); //set window size setVisible ( true ); }//end try //detect problems interacting with database catch ( SQLException sqlException ){ JOptionPane.showMessageDialog( null, sqlException.getMessage(), "Database Error", JOptionPane.ERROR_MESSAGE ); System.exit( 1 ); } //detect problems loading database driver catch ( ClassNotFoundException classNotFound ){ JOptionPane.showMessageDialog( null, classNotFound.getMessage(), "Driver Not Found", JOptionPane.ERROR_MESSAGE ); System.exit( 1 ); } //ensure statement and connection are closed properly finally{ try { statement.close(); con.close(); } //handle exceptions closing statement and connection catch(SQLException sqlException){ JOptionPane.showMessageDialog( null,

sqlException.getMessage(), "Database Error", JOptionPane.ERROR_MESSAGE ); System.exit( 1 ); } } }//end NSBEdatabase constructor //launch the application public static void main( String[] args) { BooksDataBase window = new BooksDataBase(); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } //end class DisplayMembers

Lab 14.2 Database Query

Lab 15: Java Time

Lab 16 Cryptography: Encryption and Decryption (Caesar Cipher and RSA)


Lab Objectives: After this lab, the students should be able to ? ? ? Explain the simple concepts of encryption and decryption to protect information in transmission. Explain the concepts of cryptography, symmetric key, public keys and private keys used in practice. Write programs that encrypt and decrypt data files using the simple C programming expertise acquired from the first few weeks of C instructions.

Backgrounds: Cryptography is the study to convert or encode the text so that it is unintelligible to the common people, but the designated received can use an algorithm to easily recover the original text. The original text is called plaintext, while the encoded (or encrypted) text is called cipher text. Caesar cipher is an old easy algorithm used in the history by the Roman emperor Julius Caesar. Caesar cipher uses a fixed key k, with 1 <= k <= 25, and every character of the plaintext is shifted by the fixed key k to a new character. For example, if k = 2, then a-> c, b -> d, c -> e etc. (and also the upper case characters A -> C, F -> H etc.). To decipher the cipher text, you just use k or the inverse of the key k with -1 >= -k >= -25 to shift (and wrap) to decipher if you know what key k was used to encrypt. In case you dont know what key k was used but you know Caesar cipher was used to encrypt, then you can (by brute force) manually try all combinations of -1, -2, , up to 25 (or in the lab assignment, try programmatically a for loop to decipher).

The left picture from the web page http://en.wikipedia.org/wiki/Caesar_cipher shows how the characters A -> D, B > E, C -> F (and Z -> C etc.) with a key = 3. To decipher from a cipher text, the user just apply the shift backward or use k = 3 (k = 23) to recover and get plaintext.

Note that at the end, the characters are wrapped around. Hence Z + 1 = A here (although from the ASCII table, Z + 1 = {. Caesar cipher is very easy to comprehend. However, manually shift a long string by k to encrypt and manually shift by k to decipher and also wrap around at the end is not trivial. Cryptanalysis of Caesar Cipher: Caesar cipher is readable for the receiver with a key or with enough patience (manually) or with a program. For a stranger like a cracker who intercepts the message, it is readable by trying all 25 key combinations. This is not secure at all. How to program Caesar cipher: If we do not wrap around at the end of characters, or if Z + 1 = {, the next character in ASCII table, then the code is very simple. The following two lines of code will basically shift every character in the string of plaintext by the key k
for (int i = 0; i < strlen (BUFFER); i ++) BUFFER [i] += key;

Here BUFFER is the string or plaintext input. The output and input of this kind of Caesar cipher will be like below for k = 5.

Since wrap around is needed, i.e. Z + 1 = A, a modulo 26 operation needs to be considered, and we need the following code snippet to perform the job for the upper case characters (MODBUFFER is the encrypted string from input BUFFER).
for (int i = 0; i < strlen (BUFFER); i ++) { if (BUFFER [i] >= 'A' && BUFFER [i] <= 'Z') // For an upper case character if ((BUFFER [i] + key)> 'Z') // Wrap around { MODBUFFER [i] = (BUFFER [i] - 'A' + key) % 26 + 'A'; // cout << " Is " << MODBUFFER [i] << endl; } else if((BUFFER [i] + key) < 'A') MODBUFFER [i] = (BUFFER [i] - 'A' + key + 26) % 26 + 'A'; else MODBUFFER [i] = BUFFER [i] + key;

For the if (BUFFER[i] + key) > Z for encryption wraparound, the code BUFFER[i] A computes the offset of the upper case character from A as 0 to 25, and since BUFFER[i] A can be bigger than or equal to 26, we use % 26 to reduce that to be between 0 and 25 and then add back A to get an upper case character between A and Z. The code for if((BUFFER [i] + key) < 'A') is for decryption when key is negative (if you use key = 3 to encrypt, then you use key = -3 and the same code to decrypt). Pre-lab:

Labs:

Cryptography

16.1 Lab Assignment: Caesar Cipher


Step 1. Write a C program to read a string input, a key k, 1 <= k <= 25 and then encrypt that. The string can consist of upper case and lower case characters. Both upper case and lower case characters will be shifted and then wrapped around. The string can contain special characters such as (space), , (comma), . (period) etc., and your code will not shift the special characters. As a way to verify your program, with the input Rome is not built in one day., the output will be Urph lv qrw exlow lq rqh gdb. Note you will include the above code snippet to shift and wrap around upper case characters, and with minor modifications you will write code to handle the shift and wrap around of lower case characters, and also two lines of simple code to handle special characters. Step 2. Write a C program to decipher a string encrypted by the encryption program from step 1. The program will be simple since you just make key values k with -1>= k >= -25 instead of between 1 and 25 to decipher. Given a string like Urph lv qrw exlow lq rqh gdb. from step 1, you can decipher using the same code of step 1 if you know key k = 3 was used to encrypt (then you use k = -3 to decipher). You can decipher even if you dont know the key used in step 1 to encrypt by just using a for loop iterating through k = -1 to k = -25 to try out all the possible keys.

Try to decipher this string Enwr, Ermr, Erlr. (hint: if your program works, you should see three Latin words starting with the same character: they translate into English as I come, I see, I conquer..

2. RSA Cipher
Caesar cipher used a key k to encrypt and a key k to decrypt. This kind of encryption is called symmetric key encryption. There are more sophisticated ways (algorithms) of encrypting using symmetric keys (i.e. deciphering is done in the reverse way). The famous one are DES (Data Encryption Standard) and AES (Advanced Encryption Standard) which are not covered here (see reference). RSA is a kind of asymmetric cipher in which encryption and decryption employ different key. The encryption of RSA uses a public key pair (e, n) where n = pq is the product of two different prime numbers p and q; while the decryption uses a private key d. RSA was developed by Ron Rivest, Adi Shamir, and Len Adelman at MIT in 1977. An integer P will be encrypted as C = Pe (mod n), and P can be derived from C by P = Cd (mod n) where de = 1 (mod (p-1)(q-1)). The proof of that P can be derived from C is in Appendix 2. Procedure to encrypt and decipher: To encrypt a string message M, it is first converted into message blocks M1, M2, , Mn (each block can consist of 1 to some number k of characters). Then each message block Mi is mapped to an integer Pi (by an array for example). From Pi we calculate Ci as in the previous paragraph and then we send out the integer sequence C1, C2, .., Cn (or if Ci can be mapped to a message block Ni, then we send out message N1N2N3.Nn). Distribution of the public key (e, n); the holder of the key computes two prime integer p and q ? p. Then he / she computes n = pq and picks e with e relatively prime to p- 1 and also to q -1 (otherwise private key d can not be computed). Then the holder computes d based on the equation de = 1 (mod (p-1) (q-1)). The public key pair (e, n) is disclosed to the public while the holder keeps the private key d confidential. When people send the holder messages, they encrypt using (e, n) and the procedure to encrypt described earlier. The holder uses the private key d to decrypt (the same procedure but different key). Cryptanalysis of RSA: A cracker can decipher a message encrypted by (e, n) only if he / she knows the two factors p and q of n = pq. When that is the case, the cracker can use de = 1 (mod (p-1)(q-1)) to solve d first, and then use the procedure to decipher above to decipher the message.

The factorization of n into p * q is computing feasible only if both p and q are small enough. Remember in lab 2 you wrote a program to check if an integer n is prime by checking up to n . Theoretically you need to check all integers from 2 to n , to find a proper divisor of n. When we pick big primes p and q both of at least 50 digits (so n is 100 digits or more), then there will be 1050 modulo operations if (n % j == 0) for 2 <= j <= n by the brute force way. Suppose your computer is 1000 MIPS or 109 operations a second, this will be 1041 seconds or at least 10 36 days to find the prime divisor p < q of n. This is computationally infeasible or impossible. RSA is non-crackable in this sense and in the RSA website there are many integers made to challenge people such as RSA-100 of 100 digits, RSA-200 of 200 digits etc. Now we want to tackle RSA with small (e, n) so that n = pq is doable

16.2.1 Lab Assignment: Factorization of an integer n into p q.


Write a C program that Step 1. reads an integer n from the keyboard (note you can pick n int type, hence at most 31 bits or 2 31 1). It is also OK if you want to pick n of Int64 type (of 63 bits). Step 2. Write a for loop as below to check if there is any factor j > 1. for (int j = 2; j <= square root of n; j ++) { If (n % j == 0) { factorizable = true; break; } } Step 3. If there is no such factor, print the message n is not factorizable. If there is such a factor j, check programmatically if j is a prime and n / j is a prime (you have written Lab 1.2 assignment to check if an integer k is a prime). Also check if j and n / j are the same. Step 4. Test your program with the following 4 integers n1, n2, n3, n4 n1 = 17437, n2 = 10379, n3 = 10099, n4 = 11449. Note one of these 3 integers is a prime, another one is the product of 3 primes, and the third one is the product of two identical primes (a square), and the fourth one is the product of two different primes; they are not necessarily in the order of n1, n2, n3, and n4.

16.2.2 Lab Assignment. RSA encryption


Step 1. prompts inputs for a public key pair e and n, a string M to be encrypted, Step 2. computes the private key d if n is factorizable into n = pq or prints out an error message if that is impossible (such as n is a prime itself, n = pqr, n = p2 etc. or n is too big). Step 3. Maps M into message blocks M1, M2, .., Mn of two characters each (if M is of odd length, append a packing character ). Step 4. Map each character to an integer using an array (for example, A to 0, B to 1, .., Z to 25, a to 26, ., z to 51, to 52, . to 53). For the two characters c1i and c2i of block Mi we get n1 and n2 with 0 <= n1, n2 <= 51. Now map Mi to Pi = n1 * 100 + n2. For example if Mi = ID, then we have I -> 8, D -> 3 so Mi -> Pi = 803. Step 5. Now use this code snippet to compute Ci = Pi e(mod n) int C = 1; for (int j = 1; j <= e; j +=) { C *= P; C = C % n; } Step 6. Answer what will be different if you use the following code snippet instead. The difference now is that C = C% n is done after the for loop or the multiplications. int C = 1; for (int j = 1; j <= e; j +=) { C *= P; } C = C %n; Step 7. Test your program with (e, n) = (17, 2773) and also with (e, n) = Test with this string Rome is not built in one day.

16.2.3 Lab Assignment: Decipher RSA


You can modify the previous program by deciphering with d and n (which is part of public key). Write a C program that (assumption, you know what (e, n) you used to encrypt) Step 1. prompts for a string. Enter the string output from lab assignment 3.2.2 (say the encrypted string from Rome is not built in one day. or a string of your own.

Step 2. prompts for a private key and you enter the private key calculated from assignment 3.2.2 . Step 3. Now test with this integer sequence (assuming (e, n) = )

Lab 17: Java Security Extensions Lab 18: Java Networking

Lab 19: Java email


Lab Objectives: After this lab, the students should be able to ? ? ? Explain what Java Mail API is (in addition to the basic concepts of emails and email programming). Set up the environments and download mail extensions needed to run Java email programs for JDK and for eclipse (C++ does not need environment setup). Design and run simple Java mail programs.

Background: Javas mail API to support email capabilities is an extension of standard Java and is not included in standard J2SE (or common jdk). It has to be downloaded first. The zip file can be downloaded from http://java.sun.com/products/javamail. In this web site, there is also a link to FAQ (freque ntly asked questions) that can answer many common questions: http://java.sun.com/products/javamail/FAQ.html Once downloaded, you can expand and extract the important JAR (Java Archive) file called mail.jar which includes all the .class files used in Java Mail API. You need one more Java jar file called activation.jar which can be downloaded from http://java.sun.com/products/javabeans/jaf. Using the jar files:

For JDK: You will use javac classpath and java classpath to specify where you put mail.jar and activation.jar to do the compilation and run. The proper syntax is: javac classpath .;<dir>\mail.jar;<dir>\activation.jar with ; separating the entries and . as the first entry meaning the current directory. For eclipse: After you create a project for email purpose (say if you use Assimilator.java file later on), you may see red wiggles under the uncompilable code (and under the java file) like below:

You will add the jar files to this project. This is done by following Project => Properties link in eclipse and then add the jar files as External Jar files.

Pre-lab Code of Assimilator.java from Elliote Rusty Harolds Java Network Programming import javax.mail.*; import javax.mail.internet.*; import java.util.*; public class Assimilator { public static void main(String[] args) { try { Properties props = new Properties(); // props.put("mail.host", "mail.charter.com");

props.put("mail.host", your_mail_ server_name); Session mailConnection = Session.getInstance(props, null); Message msg = new MimeMessage(mailConnection); Address bill = new InternetAddress("god@microsoft.com", "Bill Gates"); // Address elliotte = new InternetAddress("elharo@metlab.unc.edu); Address elliotte = new InternetAddress("elharo@metlab.unc.edu);

msg.setContent("New message again again. Hi Resistance is futile. You will be assimilated!", "text/plain"); msg.setFrom(bill); msg.setRecipient(Message.RecipientType.TO, elliotte); msg.setSubject("You must comply."); Transport.send(msg); } catch (Exception ex) { ex.printStackTrace(); } } } Step 1. Type the code or download the code. Step 2. Follow the steps below to add the jar files to eclipse. Step 3. Select Project => Properties, you should see this dialog popping up

Step 4. Click the button Add External JARS Step 5. Navigate to the folder you stored mail.jar and activation.jar. Click Open after you select both jars.

Lab:

Lab Assignment 19.1 Java email


Step 1. Try the code Assimilator.Java put later on in the prelab section. If you compile with javac Assimilator.java without any classpath setup, these are the error messages you will get quite a few messages, and the first few are listed here. Assimilator.java:1: package javax.mail does not exist import javax.mail.*; ^ Assimilator.java:2: package javax.mail.internet does not exist import javax.mail.internet.*; ^ Assimilator.java:13: cannot find symbol symbol : class Session location: class Assimilator Session mailConnection = Session.getInstance(props, null); ^ Now try the command javac classpath .;C:\Java\mail.jar;C:\Java\activation.jar where C:\Java is the folder you put the jar files mail.jar and activation.jar in (the general syntax

is javac classpath .;<dir>\mail.jar;<dir>\activation.jar where dot (.) and semicolon (;) start after the double quote, followed by your directory <dir>, backslash (\), then mail.jar etc.).

Lab 20: Java Servlets


Lab Objectives: Background: Pre-lab: Lab:

Basic Ideas of J2ME


The labs up to lab 20 are basic and intermediate labs on J2SE (Java Standard Edition) with downloadable extensions like mail extensions for Java email, 3D graphic extensions like Java 3D graphics extensions. J2SE programs run on host or personal computers. Sun Micro provides another technology to be run on a different platform, the embedded mobile devices. This technology is named J2ME (Mobile Edition). J2ME applications can be emulated on PC using emulators. After verifying applications run on the emulators, they can also be loaded to the appropriate embedded mobile devices to run as embedded applications. CDC / CLDC

Java Wireless Toolkit (KTool)


There are many J2ME IDE tools freely downloadable. For example eclipse can be enhanced by installing the mobile pack from eclipseme.org. There is another Java IDE called NetBeans. And NetBeans can also support the mobile pack. All the J2ME IDEs however are running on top of Java Wireless toolkit (just like all J2SE IDEs are running on top of JDK). You can download Java Wireless Toolkit from java.sun.com J2ME link.

Installation of KToolBar in C drive


After installation, it creates a folder c:\WTKxx in your computer where xx is the current version of the toolkit. In the authors computer c:\WTK22 is created since the author downloaded and installed j2me_wireless_2_2-windows.exe file.

Start KToolBar:
There are three ways to start KTool (you may start multiple copies of KtoolBar). Way 1: Use mouse to navigate <Start> button at lower left => All Programs => J2ME Wireless Toolkit 2.2 (or x.x) => Ktoolbar. Way 2. Navigate in Windows or in console window to C:\WTK22\bin and then click ktoolbar.exe.

Way 3. After navigation to C:\ wtk22\bin, click ktoolbar.bat (the batch file instead of an executable). A console window will pop up executing all the commands in the batch file and at the end, start Ktoolbar as a child process of this command window. Note you have to keep the command window open with

Run KToolbar in H drive or via network


Note if you are trying to run KToolbar in the school computers where you can not install the Java Wireless Toolkit, there is a way to get around. The instructor has to install this toolkit in his / her own C driver as above. Then copy the c:\wtk22 to the network as for example h:\instructor\wtk22. You may start ktoolbar.exe not from the exe file but from the ktoolbar.bat, the batch file. This batch file contains the paths for the environments and also it will execute the exe file. If you install WTK22 in the network drive, it is possible that you can not run ktoolbar.exe since it can not find the necessary paths. You may modify the paths in ktoolbar.bat accordingly. For example, When creating a new project, doubly click New Project in the J2ME Wireless Toolkit dialog. The following New Project dialog pops up. You can enter any name for the Project Name as long as it is not used before. The field MIDlet Class Name has to be filled with the class name of the Java file which has the line public class <Midlet> extends Midlet, where <Midlet> is the name of the class, that also agrees with the name of the java file. For example, if you have a J2ME Java file called HelloMidelt.Java, thenit should have a line called public class HelloMidlet extends MIDlet where the class name

HelloMidlet agrees with the file name. Type in HelloMidlet in the field MIDlet Class Name for this case.

After you enter the two fields, click the button Create Project. A dialog should pop out as follows. Click the button OK to close the dialog now.

Figure J2ME-3. Dailog when creating a project name test2 with Midlet Class Name HelloMidlet.

At this moment, a project subfolder called test2 was created under C:\WTK22\apps (or the corresponding C drive, H drive depending on where you installed or copied your WTK22\bin directory. There are 4 subfolders under this C:\ WTK22\apps\test2: bin, lib, res, and src as well a file called project.proeprties. If you click open the bin directory, youll see files called test2.jad and MANIFEST.MF, where test2.jad is a Java Application Descriptor file with file name the same as the project name; the other 3 folders are empty now.

Youll see error message Build failed and you can also see in the message area saying no sources to compile. Now copy this file HelloMidlet.java to the src subfolder (which is in website www.csupomona.edu/~hlin/LabManuals/Javamanuals.htm, this is file from Quasay Mamhouds Wireless Java, chapter 1. After copying this file to the src subolder under c:\WTk22\apps\test2\src, you should see two new folders created under test2: class and tmplcass, both of them contain a file name HelloMidlet.class.

Now you can click Build again in the J2ME Wireless Toolkit dialog. This time the build successful message should appear as follows:

You can now try to run the J2ME application. Click Run, and a cellular phone emulator should appear.

The text showing Launch The button corresponding to Launch

If you click the button below Launch (the one to the right of the select button, you will see hello World if that works.

Palm OS Emulator (POSE)


Convert Midlet files for Palm Emulation:

J2ME programs could be run on Palm OS Emulator as well as real Palm devices (after conversion). Running KToolbar will generate a jad file in the bin directory of the corresponding applicatio n.

It is possible to generate the corresponding jar (Java Archive) also in the bin directory of the application by following Project =>Package => Create Package

Download mid4palm1.0.zip (Midlet file for Palm) from http:\\java.sun.com\\products or available resource and expand. There is a folder Converter which contains a Converter.jar file. Start a DOS console window and navigate to the folder for Converter. Type java jar Converter.jar in the prompt. This will start an application called PRC converter tool. Follow File =>Convert, it will pop up a dialog for you to find a path.

Navigate to the folder that contains the jad file (test2.jad in this case). Verify that you also have the corresponding jar file by the previous create package command from KToolbar.

If you convert successfully, you should see the Successful message in the PRC Tool Window. Also, check the applications bin window to make sure you have created a PRC file (test2.prc file). This PRC (Palm Resource Code) file is the file that can run on Palm OS emulator or real Palm device. Get Palm OS emulator Files: You can download Palm OS emulator from http://www.palmsource.com with a file name like emulator-win.zip. You also have to download some RAM images that emulate the appearance of some Palm devices.

Lab 21 Hello World In J2ME


Lab Objectives: After this lab, the students should be able to: ? ? ? ? ? ? Explain what the second technology J2ME of Java is, in addition to the familiar J2SE, the standard edition. Download and set up the necessary configuration to run a J2ME application Build a J2ME application in the normal case Fix simple problems encountered in building a simple J2ME application Run a simple J2ME application Fix simple problems when running a simple J2ME application

Background: Pre-lab: 1. Download J2ME wireless toolkit or copy the folders \WTK22\bin 2. Lab:

Lab 21.1 Run Hello World in Color Cellular Phone Emulator


In the first few steps of this lab assignment, you will just repeat the instructions in the Basic Ideas of J2ME. Make sure you have J2ME Wireless Toolkit.

Lab 21.2 Run Hello World in Palm OS emulator

Lab 22: Stock Quotes Lab 23: J2ME Games

Appendix:
Appendix A: Using JDK
JDK stands for Java Development Kit. This consists of the Java commands and libraries needed to run Java programs. JDK can be run directly in console windows of Windows OS. IDE (Integrated Development Environment) Java tools run on top of JDK and have to be installed after installing JDK. Case when there is no JDK in your computer JDK can be freely downloaded from Sun Micros web site: http://java.sun.com . As of summer 2006, JDK 1.5 (also called JDK5.0) is the most current version. When downloading, make sure you download from the J2SE (Java Standard Edition) link of the download page; there are other freely downloadable files: J2ME wireless toolkit for mobile computing and J2EE SDK for Java Enterprise Edition that you may want to use later. JDK1.5 update 8 for example is a file of about 50M bytes with the name jdk-1_5_0_08windows -i586-p.exe (Note JDK version and update may be more current the time you download). After you download, click the exe file to install the JDK automatically. For JDK1.5, it should be installed in the folder C:\Program Files\ Java. Case when there is JDK in your computer (this is the case if you use a school computer with JDK installed or if you download and install as above). Start a command window (also called console window or DOS window) by clicking Start => Run as in Figure 1.

Start

Run

A small window pops up prompting you to enter some command.

Type cmd in the textbox after the prompt Open to start the command window (note you can type some other program names to start some other Window programs. For example, typing inetmgr starts the IIS, Internet Information Server, typing regedit starts registry edit,

Type the command java inside the command window. You should see a screen capture like above starting with Usage: java [-options] . If instead of the above, you see a message saying that java is not recognized as an internal command or external command.. as follows, there are two possibilities. Possibility one: JDK is not installed. Check the folder C:\Program Files\Java \jdk****\bin to see if there is a file called java.exe (here jdk**** means the current version of JDK, which is jdk1.5.0_02 for the authors computer.). Possibility two: the PATH variable is not set up correctly. When executing a command in the current directory the operating system checks first the current directory for the file, and then checks all paths sequentially defined in the PATH environment variable. You can find out what are the paths defined by PATH by typing path after the command prompt. If the jdk path is not in the paths, you can set it by typing: SET PATH=%PATH%;<your JDK install directory>, in the authors case the command is SET PATH=%PATH%;C:\PROGRAM FILES\JAVA\JDK1.5.0_02\BIN

Appendix B: Using IDE Eclipse

Vous aimerez peut-être aussi