Sunteți pe pagina 1din 80

Professional Java 1000 - 3000

How To Java

Student Materials
&
Lab Exercises
Professional Java How To Java

(this page is blank)

Lab Exercise Guide Page 2 of 80 Soft9000.com


Professional Java How To Java

Welcome!

This document contains the full set of training materials required to


complete Professional Java: How To Java sessions 1000, 2000, and
3000.

The videos accompanying this training are available on YouTube.

Enjoy the training!

Randall Nagy
rnagy@Soft9000.com

YOUR PRODUCT ACCESS CODE IS: 1121-2571-4181

Lab Exercise Guide Page 3 of 80 Soft9000.com


Professional Java How To Java

(this page is blank)

Lab Exercise Guide Page 4 of 80 Soft9000.com


Professional Java How To Java

Contents
Step-By-Step Lab Guide ............................................................................................. 8
Solution Files ......................................................................................................... 8
Activity 01: Java Main ............................................................................................... 10
Objective ............................................................................................................. 10
Overview ............................................................................................................. 10
Step by Step Guide ................................................................................................ 10
Step 01: Java Compiler ....................................................................................... 10
Step 02: JavaMain .............................................................................................. 11
Step 03: Program Verification .............................................................................. 12
Exercise 01: Reading Integral Input ............................................................................. 13
Objective ............................................................................................................. 13
Overview ............................................................................................................. 13
Step by Step Guide ................................................................................................ 13
Step 01: Project Tooling ..................................................................................... 13
Step 02: Project, Package, & Class Creation (Eclipse) ............................................. 14
Step 03: Testing the JDK (all versions) ................................................................. 15
Step 04: Running JavaOne (Eclipse) ...................................................................... 16
Step 05: Reading Console Input (all versions) ......................................................... 17
Step 07: Program Verification .............................................................................. 19
Exercise 02: Classic Console Loop .............................................................................. 20
Objective ............................................................................................................. 20
Overview ............................................................................................................. 20
Step by Step Guide ................................................................................................ 20
Step 01: Our New Package .................................................................................. 20
Step 02: Creating a Forever Loop ..................................................................... 21
Step 03: Program Re-factoring ............................................................................. 22
Step 04: Import Saves Typing .............................................................................. 23
Step 05: Program Verification .............................................................................. 24
Exercise 03: Using Arrays.......................................................................................... 26
Objective ............................................................................................................. 26
Overview ............................................................................................................. 26
Step by Step Guide ................................................................................................ 26
Step 01: Exporting Projects (Eclipse & derivations) ................................................. 26
Step 03: Renaming & Deleting Projects (Eclipse & derivations) ................................. 28
Step 04: Creating & Displaying Arrays .................................................................. 29
Step 05: Processing MainMenu Responses ............................................................. 32

Lab Exercise Guide Page 5 of 80 Soft9000.com


Professional Java How To Java

Step 06: Program Verification .............................................................................. 33


Appendix A: Questions & Activities ............................................................................ 38
Professional Java 1100: Answers & Solutions ............................................................. 38
Professional Java 1200: Answers & Solutions ............................................................. 42
Professional Java 2100: Answers & Solutions ............................................................. 48
Professional Java 2200: Answers & Solutions ............................................................. 54
Professional Java 3100: Answers & Solutions ............................................................. 61
Professional Java 3200: Answers & Solutions ............................................................. 67
Appendix B: Setup Instructions .................................................................................. 76
Objective ............................................................................................................. 76
Overview ............................................................................................................. 76
Step by Step Guide ................................................................................................ 76
Step 01: Downloading Software Developer Support Files .......................................... 76
Step 02: Installing The JDK ................................................................................. 78
Step 03: Installing Eclipse ................................................................................... 80
Step 04: Download Training Support Files ............................................................. 80

Lab Exercise Guide Page 6 of 80 Soft9000.com


Professional Java How To Java

(this page is blank)

Lab Exercise Guide Page 7 of 80 Soft9000.com


Professional Java How To Java

Step-By-Step Lab Guide

This guide has been designed so as to allow students to reason their way through a real-world
problem statement. While experienced students seldom need to look at the final solution,
even experts can be glad to have a completed solution when trouble arises.

Solution Files

If you run into trouble completing a lab, the first thing to do is to locate and extract the
solution from the main solution archive. Named LabSolutions.zip once the solution files are
extracted you will discover that there are two types of archives: One designed for use with
Eclipse, and one designed for use with Netbeans. If you are not using either Eclipse or
Netbeans, there is no need to worry. Students can still open and use the source code in any
archive with any other Java development environment.

While the source code can be copied from any archive into any Integrated Development
Environment (IDE), those who are using either Netbeans or Eclipse will also find detailed
instructions on how to identify & import the appropriate solution either tool set herein.

The instructions documenting how to import the solutions to the lab exercises are located in
the appendices at the end of this document.

The complete set of source code has also been included in the appendix of this document.

Lab Exercise Guide Page 8 of 80 Soft9000.com


Professional Java How To Java

(this page is blank)

Lab Exercise Guide Page 9 of 80 Soft9000.com


Professional Java How To Java

Activity 01: Java Main


Objective
Jump in & enjoy some hands-on practice writing Java Programs.

Overview
You will be performing the following tasks:
Creating a Java Console Application
Compiling, testing, and & running Java Programs
Using System.out to display messages

Step by Step Guide

Solution File: (none)


Starter File: (none)

Step 01: Java Compiler

You do not need anything fancy to write Java. All that is required is a version of the Java
compiler!

To see if you have a version of Java installed:


1. Open a command-line (also known as a terminal) prompt:
2. On Microsoft Windows, Select Start then open Accessories.
3. Under the Accessories folder, you will see either an MSDOS or Command
Prompt Icon.

4. Select the same.


5. To see if you have a version of Java installed, type the word java at the command
prompt. Press enter. (quotes are not required here or elsewhere just type in the
word java then press the Enter key.)
6. To see if you have a version of Java installed, enter javac at the same prompt.
7. In order to complete this activity, you will need to have both java and well as javac
installed. If you do not have a version of the Java SDK installed, then install Java
JDK 1.7.

Lab Exercise Guide Page 10 of 80 Soft9000.com


Professional Java How To Java

Step 02: JavaMain

There is nothing special about Java programming files! To prove it, we will create a Java
program using a simple text-editing tool.

To create a new Java Project:


1. Enter the following to create and enter a folder called JavaMain

2. Enter the word notepad JavaMain.java at the command prompt.


3. Confirm that you want to create the file when asked.
4. A simple text-editor will appear.
5. Enter the following:

6. Double check to ensure the program looks exactly as presented above!


7. Press on the x to exit the editor. Be sure to select Yes so as to save your
changes!
8. Back at the command prompt, compile your new program by entering javac
JavaMain.java
9. If errors are displayed, go back to item 2 (above) to correct any problems.
10. Once no errors are shown, you can run you & see your messages by entering
java JavaMain.class at the command prompt.

Lab Exercise Guide Page 11 of 80 Soft9000.com


Professional Java How To Java

Step 03: Program Verification

This completes the first Java Programming Activity.

1. Your final program should look like this:

public class JavaMain {

public static void main( String[] args ) {

System.out.println( "Hello world!" );

}
}

2. The above code can also be found in the solutions folder in the archive file
mentioned at the start of this Exercise.

(end of activity)

Lab Exercise Guide Page 12 of 80 Soft9000.com


Professional Java How To Java

Exercise 01: Reading Integral Input


Objective
Understand how to use Java to conduct fundamental input, processing, and output
activities.

Overview
You will be performing the following tasks:
Creating a Java Console Application
Compiling, testing, and & running Java Programs
Using a provided class to read console input
Using System.out to display messages

Step by Step Guide

Solution File: lab01.zip


Starter File: (none)

Step 01: Project Tooling

Professional Java Software Developers have a wide range of tools to select from. From
simple editors like Notepad on Microsoft Windows or gedit on Linux, to full-blown IDEs
such as Eclipse, NetBeans, and JDeveloper, Java can be written in many different
ways.

This training was created using the most recent version of Eclipse.

At a minimum this training assumes that the student has installed a Java Developers
Kit (JDK.) Java Version 1.7 (commonly referred to as Java 7) is the minimum research
& JDK requirement.

NOTE: When installing Java, be sure to match the version of the JDK to the proper
release of your operating system. DO NOT ATTEMPT TO USE 64 BIT JAVA ON A 32
BIT SYSTEM, OR A 32 BIT VERSION OF JAVA ON A 64 BIT SYSTEM!

If you have problems running any exercise described in these labs, be sure to verify that
your Operating System Bit-Addressing Model matches your JDK. (i.e. Be sure to use a
32 bit JDK on a 32 bit OS, 64 to 64, 128:128 (etc.))

Lab Exercise Guide Page 13 of 80 Soft9000.com


Professional Java How To Java

Before continuing to the next step:


1. Download the proper version of the 1.7 JDK (or greater.)

2. Install the JDK.

3. Download & install an IDE, or other editing tools.

Step 02: Project, Package, & Class Creation (Eclipse)

At the time of this writing, the Eclipse IDE is the most widely-used Integrated
Development Environment. The instructions for all subsequent labs assume the use of
Eclipse.

When using almost Eclipse (as well as almost any IDE), the mantra most students chant
when setting up a new Java Application is Project, Package, Class.

To create a new Java Project:


11. Open Eclipse.

12. From the main menu, select "File | New | Java Project."

13. Name the project Exercise01.

14. Press Finish. Your project is now ready for a Java Package.

To create a new Java Package:

15. Click to highlight the Exercise01 Project-Name

16. From the main-menu, select File | New | Package.

17. Accept the default source folder, and provide the name com.soft9000 for the
new package name.

Lab Exercise Guide Page 14 of 80 Soft9000.com


Professional Java How To Java

18. Press Finish.

To create a new Java Class:

19. Click to highlight the Exercise01 Project-Name.

20. From the main menu, select "File | New | Class."

21. Place the class into the com.soft9000 folder by providing the package name
com.soft9000 in the class creation dialog.

22. Next, provide the name JavaOne as the class name.

23. Most versions of Eclipse also allow us to have a main member function created
automatically. If you version supports that feature, then select it:

24. Press Finish.

Step 03: Testing the JDK (all versions)

Once a basic Project, Package, & Class have been created, writing Java is universally
the same. While the viewer shown by each Java editor might look a little different, the
Java source code (programs) can be exchanged.

Editing JavaOne.java:

1. Most IDEs will have a package view along the left-hand side. By clicking on the
icons, both projects & packages can be explored.

2. Locate and open JavaOne.

Lab Exercise Guide Page 15 of 80 Soft9000.com


Professional Java How To Java

3. After any automatically-created comments, the code for you basic Java program
will look like:

package com.soft9000;

public class JavaOne {

public static void main(String[] args) {

}
}

4. If you are missing a main() method as depicted above, then edit the default file
so at to manually provide one.

5. In order to ensure that the JDK has been properly installed, add the following
statement:

package com.soft9000;

public class JavaOne {

public static void main(String[] args) {


System.out.println("Greetings, Humanoid!");
}
}

6. Be sure to end the statement with a semi-colon! (;)

Step 04: Running JavaOne (Eclipse)

Once errors have been eliminated from a program, the next task is to run it!

Running JavaOne:

1. Most IDEs will have a quick way to right-click & run a program.

2. On Eclipse, the best way to run any program with a main() method is to right-click
on the program view (JavaOne) to select Run as Java Application.

3. After the program has run successfully, the message Greetings Humanoid will
appear in the IDEs Console or Output Tab.

Lab Exercise Guide Page 16 of 80 Soft9000.com


Professional Java How To Java

4. Either of those Views will be located along the bottom of the page.

5. If you do not see the message, then check your program for errors. If you are
able to locate but unable to correct any errors, please search for an answer to
you problem on the Internet. Use key phrases from the error message to help
pinpoint a solution to the problem.

Step 05: Reading Console Input (all versions)

Once we have verified that the JDK has been installed properly, we can begin our next
development task.

Managing Input, Processing, and Output:

3. The first tack is to create a way to read the keyboard. To create a member
function that can read the keyboard, insert the following 2 statement directly after
the package statement at the top of JavaOne:

import java.io.IOException;
import java.io.InputStream;

4. Next, add the following directly before the main() in JavaOne:

public static int readInt(InputStream in) {


try {
return in.read();
} catch (IOException e) {
return -1;
}
}

5. Do not be concerned if you do not understand what is taking place in the above
code. We will cover keywords such as try and catch in other lessons.

6. Your program should now look like:

package com.soft9000;
import java.io.IOException;
import java.io.InputStream;

Lab Exercise Guide Page 17 of 80 Soft9000.com


Professional Java How To Java

public class JavaOne {

public static int readInt(InputStream in) {


try {
return in.read();
} catch (IOException e) {
return -1;
}
}

public static void main(String[] args) {


System.out.println("Greetings, Humanoid!");
}
}

7. Most IDEs will have a quick way to right-click & run a program.

Step 06: Calling Member Functions

The member function readInt() has been assigned the task of reading any keyboard
data. While it is not apparent at the moment, readInt() has been designed to work with
System.in, as well as any similar type of InputStream.

Do the following:

8. Complete the main() by providing the following implementation:

public static void main(String[] args) {


System.out.println("Greetings, Humanoid!");
System.out.println("We computers like numbers.");
System.out.print("Press a key on the keyboard, ");
System.out.println("then press 'Enter'...");
int option = readInt(System.in);
if(option == 10) {
System.out.println("SPECIAL KEY DETECTED!");
}
System.out.println("That int was [" + option + "]!");
}

9. Correct any errors. Be sure each statement ends with a semicolon!

10. Notice the difference between .print() and .println().

11. Compile and run the application.

Lab Exercise Guide Page 18 of 80 Soft9000.com


Professional Java How To Java

12. Which keys generate the special character?

Step 07: Program Verification

This completes the first Java Programming exercise.

1. Your final program should look like this:

package com.soft9000;

import java.io.IOException;
import java.io.InputStream;

public class JavaOne {

public static int readInt(InputStream in) {


try {
return in.read();
} catch (IOException e) {
return -1;
}
}

public static void main(String[] args) {


System.out.println("Greetings, Humanoid!");
System.out.println("We computers like numbers.");
System.out.print("Press a key on the keyboard, ");
System.out.println("then press 'Enter'...");
int option = readInt(System.in);
if (option == 10) {
System.out.println("SPECIAL KEY DETECTED!");
}
System.out.println("That int was [" + option + "]!");
}
}

2. The above code can also be found in the solutions folder in the archive file
mentioned at the start of this Exercise.

(end of lab)

Lab Exercise Guide Page 19 of 80 Soft9000.com


Professional Java How To Java

Exercise 02: Classic Console Loop


Objective
Understand how to use Java to conduct looping input, processing, and output activities.

Overview
You will be performing the following tasks:
Learn how to cut & paste code between Projects
Updating the results from the previous exercise
Creating a never ending key-processing loop
Re-ractoring JavaOne into two different packages & classes
Utilizing the classic import paradigm
Migrating between fully qualified & imported names

Step by Step Guide

Solution File: lab02.zip


Starter File: (none)

Step 01: Our New Package

We will be using a new package to continue the work from the previous exercise.

To create a new Java Project:

25. Open Eclipse.

26. From the main menu, select "File | New | Java Project"

27. Name the project Exercise02

28. Press Finish. Your project is now ready for a Java Package.

To create a new Java Package:

29. Click to highlight the Exercise02 Project-Name

30. From the main-menu, select File | New | Package.

Lab Exercise Guide Page 20 of 80 Soft9000.com


Professional Java How To Java

31. Accept the default source folder, and provide the name com.soft9000 for the
new package name.

32. Press Finish.

To create a new Java Class:

33. Click to highlight the Exercise02 Project-Name.

34. From the main menu, select "File | New | Class."

35. Place the class into the com.soft9000 folder by providing the package name
com.soft9000 in the class creation dialog.

36. Next, provide the name JavaOne as the class name.

37. Press Finish.

Step 02: Creating a Forever Loop

We will use the implementation from the previous exercise.

Do the following:

13. Open the previous solution for JavaOne in the Exercise01 Project.

14. Right-click to choose Select All, then Copy (ctrrl+c) to place the content on the
clipboard.

15. Open the newly-created JavaOne class in the Exercise02 Project.

16. Right-click to choose Select All, then Paste (ctrrl+v) to replace the default
program with the content on the clipboard.

17. Replace the main() with the following implementation:

public static void main(String[] args) {


System.out.println("Type some words, then press 'Enter.'");
int option = readInt(System.in);
while (option != 10) {
System.out.println("Integer = [" + option + "]!");

Lab Exercise Guide Page 21 of 80 Soft9000.com


Professional Java How To Java

option = readInt(System.in);
}
System.out.println("SPECIAL KEY DETECTED!");
}

18. Correct any errors. Be sure each statement ends with a semicolon!

19. Compile and run the application.

20. Notice that while a single key is pressed, that the special character is what is
received when the enter key is pressed.

21. Notice also that unlike the previous lab the while loop allows us to see that
System.in keeps track of all input typed.

Step 03: Program Re-factoring

Renaming, copying, and migrating pieces of a program is know as re-factoring. In this


step, we will move the the readInt() from JavaOne, to another class & file.

Do the following:

22. Create a new package. Name the package com.soft9000.helpers.

23. Create a new class in the helpers package. Name the class Reader.

24. Open JavaOne. Cut and paste the entire readInt() member into the Reader class,
as well as the two required import statements.

25. Your implementation should look like:

package com.soft9000.helpers;

import java.io.IOException;
import java.io.InputStream;

public class Reader {

public static int readInt(InputStream in) {


try {
return in.read();
} catch (IOException e) {
return -1;

Lab Exercise Guide Page 22 of 80 Soft9000.com


Professional Java How To Java

}
}
}

26. Now that .readInt() had bern moved to com.soft9000.helpers.Reader, JavaOne


will be unable to find it.

27. Update JavaOne to use the fully-qualified path name.

28. Your code should look like the following:

package com.soft9000;

public class JavaOne {

public static void main(String[] args) {


System.out.println("Greetings, Humanoid!");
System.out.println("We computers like numbers.");
System.out.print("Press a key on the keyboard, ");
System.out.println("then press 'Enter'...");
int option =
com.soft9000.helpers.Reader.readInt(System.in);
if (option == 10) {
System.out.println("SPECIAL KEY DETECTED!");
}
System.out.println("That int was [" + option + "]!");
}
}

29. Open the previous solution for JavaOne in the Exercise01 Project.

30. Right-click to choose Select All, then Copy (ctrrl+c) to place the content on the
clipboard.

Step 04: Import Saves Typing

There are times when fully-qualifying package names are absolutely required (for
example, then using Javas Date class.)

In as much as we have no other Reader class visible, rather than fully-qualifying the
Reader Class, we should update JavaOne to import Reader, instead.

While updating our class to avoid a single class-qualifier is of questionable value, the

Lab Exercise Guide Page 23 of 80 Soft9000.com


Professional Java How To Java

more we use classes and functions from other packages, the more important it can be
to use import.

Do the following:

31. Add the following import statement directly underneath the package statement:

import com.soft9000.helpers.Reader;

32. Remove the prefix from the subsequent Reader statements so only the name of
the class (Reader) as well as the member name (readInt()) are present.

33. Your implementation should look like the following:

package com.soft9000;
import com.soft9000.helpers.Reader;

public class JavaOne {

public static void main(String[] args) {


System.out.println("Type some words, then press 'Enter.'");
int option = Reader.readInt(System.in);
while (option != 10) {
System.out.println("Integer = [" + option + "]!");
option = Reader.readInt(System.in);
}
System.out.println("SPECIAL KEY DETECTED!");
}
}

34. The more we use the resources from other packages, the more typing the import
statement will save!

Step 05: Program Verification

This completes the Java Programming exercise.

1. The content of Reader (Reader.java):

package com.soft9000.helpers;

import java.io.IOException;
import java.io.InputStream;

Lab Exercise Guide Page 24 of 80 Soft9000.com


Professional Java How To Java

public class Reader {

public static int readInt(InputStream in) {


try {
return in.read();
} catch (IOException e) {
return -1;
}
}
}

2. The content of JavaOne (JavaOne.java):

package com.soft9000;
import com.soft9000.helpers.Reader;

public class JavaOne {

public static void main(String[] args) {


System.out.println("Type some words, then press 'Enter.'");
int option = Reader.readInt(System.in);
while (option != 10) {
System.out.println("Integer = [" + option + "]!");
option = Reader.readInt(System.in);
}
System.out.println("SPECIAL KEY DETECTED!");
}

3. The above code can also be found in the solutions folder in the archive file
mentioned at the start of this Exercise.

(end of lab)

Lab Exercise Guide Page 25 of 80 Soft9000.com


Professional Java How To Java

Exercise 03: Using Arrays


Objective
Practice creating & using Java Arrays, as well as the iterative constructs, keywords, and
patterns.

Overview
You will be performing the following tasks:
Learn how to export & import projects from Eclipse
Learn how to rename & delete Eclipse Projects
Add a top-level menu to the previously-completed Exercise
Use arrays to manage application options
Migrate from Javas classic, to Javas static imports
Use a classic for loop to display enumerated user options

Step by Step Guide

Solution File: lab03.zip


Starter File: lab02.zip

Step 01: Exporting Projects (Eclipse & derivations)

Rather than creating a new project, we will rename the previous exercise. Those who
do not wish to save the result of the last exercise can continue to Step 02.

Eclipse users will use the export feature. Other IDE users can use the copy & past
methods described in the previous exercise, then skip directly to Step 04.

Export an existing Java Project (Eclipse & derivations, only):

38. Open Eclipse. Use the previous workspace.

39. If you would prefer to use the solution to the previous exercise rather than your
previous solution, skip to Step 02.

40. From the main menu, select "File | Export."

41. Expand the General folder to select Archive File.

Lab Exercise Guide Page 26 of 80 Soft9000.com


Professional Java How To Java

42. Check the name of the Project to include in the archive (i.e. Exercise02.)

43. Browse or otherwise specify the name of the archive file to export.

44. Press Finish.

Step 02: Importing Projects (Eclipse & derivations)

Eclipse users will use the import feature to import a previously exported Eclipse Project.

To import an existing Java Project:

1. Select File | Switch Workspace | Other.

2. Change the previous workspace name to Lab03 in the dialog.

3. After entering the new workspace name, wait for Eclipse to restart.

4. Depending upon the speed of your machine, a restart can take up to 60 seconds.

5. From the main menu, select "File | Import."

6. Expand the General tab so as to select Existing Project into Workspace

7. Click Next.

8. Check the Select archive file radio-button.

9. Browse to & select the location of the previously-exported archive file.


(Alternatively, you could also import the solution mentioned at the start of this

Lab Exercise Guide Page 27 of 80 Soft9000.com


Professional Java How To Java

Exercise.)

10. Select the name of the project to import (in this case, select Exercise02)

11. Press Finish.

12. The project has now been imported.

Step 03: Renaming & Deleting Projects (Eclipse & derivations)

Eclipse users will rename the import imported package to Exercise03.

The importation & exportation process just described restores any previous Eclipse
Project. In as much as we want to re-use that Project in this exercise, all we need do is
to rename the result of the imported exercise to Exercise03:

To rename a project:

1. Select the project to be renamed in the Package Explorer.

2. Select File | Rename from the main menu.

3. Provide a new Project Name (Exercies03)

4. Press Okay

The following information on how to destroy an Eclipse Project is informational only. No


project requires removal at this time. Official instructions resume with Step 04.

To delete a project (INFORMATION ONLY):

1. Now that we know how to rename a project, import another solution.

2. Select the imported Project in the Package Explorer.

3. Press the delete key (most version also support Edit | Delete from the main
Eclipse menu.)

Lab Exercise Guide Page 28 of 80 Soft9000.com


Professional Java How To Java

4. On the project-deletion dialog, the option to delete project content is usually


unselected for safety reasons. Be sure to SELECT the option that will DELETE
the project contents on this disk! Failure to remove project content from the
workspace / disk will prevent another same-named-project from being
created or imported.

5. NOTE: Failure to DELETE THE PROJECT-NAMED FOLDER will require either


(1) a new workspace creation, or (2) a MANUAL deletion of the project-named-
folder from the disk (underneath the workspace-folder.)

Step 04: Creating & Displaying Arrays

By this Step, Eclipse users have a Project named Exercise03.

Non-Eclipse users should have created & imported either (1) their own results from the
previous exercise, or (2) the starter file (as listed at the beginning of this exercise) into a
Project named Exercise03.

We will begin by adding a MainMenu class to JavaOne. The MainMenu class will have
an Array. The array will be used to display & manage menu-items.

1. Create a class names MainMenu in the com.soft900 Package.

2. Update MainMenu.java:

package com.soft9000;

public class MainMenu {


static String[] menu = {
"Main Menu",
"Create Record",
"Delete Record",
"List Records",
"End Program"
};
}

Lab Exercise Guide Page 29 of 80 Soft9000.com


Professional Java How To Java

3. An Array in java is simply a block of addresses.

a. Unlike arrays in other programming languages, Java Arrays also have the
ability to tell us just how many addresses (items) are being represented.

b. In the above, we have both created, as well as initialized, an array.

c. The name of the array is menu. The array manages a set of addresses
that point to a set of strings.

4. Once we have a list of menu-options, all we need do is display them! To manage


the console, add the following imports to MainMenu.java:

import java.io.InputStream;
import java.io.PrintStream;

import com.soft9000.helpers.Reader;

5. Next, update MainMenu by adding getOption() member function to the class:

public class MainMenu {

public static char getOption(InputStream in, PrintStream out) {


for (int ss = 0; ss < menu.length; ss++) {
out.println(menu[ss]);
}
return ?;
}
}

6. Lets add a test case to that ManinMenu Class, as well:

public static void main(String[] args) {


char option = getOption(System.in, System.out);
System.out.println("TESTING: Got " + option);
}

7. Take a moment to test ManiMenu by running main() as a Java Application.

Step 05: Processing Keyboard Events

Displaying a list of string is easy. Turning the display into a menu-processor requires a
little more work.

Lab Exercise Guide Page 30 of 80 Soft9000.com


Professional Java How To Java

8. Update getOption():

public static char getOption(InputStream in, PrintStream out) {


StringBuilder sb = null;
for (int ss = 0; ss < menu.length; ss++) {
sb = new StringBuilder();
if (ss == 0) {
sb.append(menu[ss]);
} else {
sb.append(ss);
sb.append(".) ");
sb.append(menu[ss]);
sb.append(".");
}
out.println(sb.toString());
}
out.print("Number: ");
char result = (char) Reader.readInt(in);
while (Reader.readInt(in) != 10) {
// do nothing!
}
return result;
}

9. Notice that:

a. a new instance of StringBuilder is used to create an enumerated string-


representation of user options.

b. Next, see how an if-statement-block works so as to prevent Main Menu


from having a menu-number.

10. Take a moment to test ManiMenu by running main() as a Java Application. If you
enter the number 5, then you should see the following:

Main Menu
1.) Create Record.
2.) Delete Record.
3.) List Records.
4.) End Program.
Number: 5
TESTING: Got 5

11. Feel free to change the MainMenu test program as desired. Be sure to close
hten save MainMenu.java so JavaOne can re-use our updates!

Lab Exercise Guide Page 31 of 80 Soft9000.com


Professional Java How To Java

Step 05: Processing MainMenu Responses

We now have a nice MainMenu processing & testing routine! All we need to do next is
to update JavaOne to MainMenu.getOption() so as to match-up user requests, to any
new program options.

To create the new program, do the following:

12. Create a new class in com.soft9000 called MyProgram.

13. Update MyProgram.java to match the following implementation:

package com.soft9000;

public class MyProgram {

public static void CreateRecord() {


System.out.println("CreateRecord");
}

public static void DeleteRecord() {


System.out.println("DeleteRecord");
}

public static void ListRecords() {


System.out.println("ListRecords");
}

14. We will complete MyProgram as part of future exercises. For now, be sure to
save the & close MyProgram so JavaOne can re-use our new creation!

Finally, we can now update JavaOne:

15. Locate & open JavaOne.

16. Provide the following implementation

package com.soft9000;

public class JavaOne {

public static void main(String[] args) {


System.out.println("Start: Welcome!");
char option = 0;

Lab Exercise Guide Page 32 of 80 Soft9000.com


Professional Java How To Java

while (option != 4) {
option = MainMenu.getOption(System.in, System.out);
if (option == '1') {
MyProgram.CreateRecord();
continue;
}
if (option == '2') {
MyProgram.DeleteRecord();
continue;
}
if (option == '3') {
MyProgram.ListRecords();
continue;
}
if (option == '4') {
break; // done!
}
System.out.println("Unknown: [" + option + "]?");
}
System.out.println("End: Thank You!");
}
}

17. Compile & run JavaOne.

Step 06: Program Verification

This completes the Java Programming exercise.

35. The content of Reader.java:


package com.soft9000.helpers;

import java.io.IOException;
import java.io.InputStream;

public class Reader {

public static int readInt(InputStream in) {


try {
return in.read();
} catch (IOException e) {
return -1;
}
}
}

Lab Exercise Guide Page 33 of 80 Soft9000.com


Professional Java How To Java

36. The content of JavaOne.java:

package com.soft9000;

public class JavaOne {

public static void main(String[] args) {


System.out.println("Start: Welcome!");
char option = 0;
while (option != 4) {
option = MainMenu.getOption(System.in, System.out);
if (option == '1') {
MyProgram.CreateRecord();
continue;
}
if (option == '2') {
MyProgram.DeleteRecord();
continue;
}
if (option == '3') {
MyProgram.ListRecords();
continue;
}
if (option == '4') {
break; // done!
}
System.out.println("Unknown: [" + option + "]?");
}
System.out.println("End: Thank You!");
}
}

37. The content of MainMenu.java

package com.soft9000;

import java.io.InputStream;
import java.io.PrintStream;

import com.soft9000.helpers.Reader;

public class MainMenu {


static String[] menu = {
"Main Menu",
"Create Record",
"Delete Record",
"List Records",
"End Program"

Lab Exercise Guide Page 34 of 80 Soft9000.com


Professional Java How To Java

};

public static char getOption(InputStream in, PrintStream out) {


StringBuilder sb = null;
for (int ss = 0; ss < menu.length; ss++) {
sb = new StringBuilder();
if (ss == 0) {
sb.append(menu[ss]);
} else {
sb.append(ss);
sb.append(".) ");
sb.append(menu[ss]);
sb.append(".");
}
out.println(sb.toString());
}
out.print("Number: ");
char result = (char) Reader.readInt(in);
while (Reader.readInt(in) != 10) {
// do nothing!
}
return result;
}

public static void main(String[] args) {


char option = getOption(System.in, System.out);
System.out.println("TESTING: Got " + option);
}

38. The content of MyProgram.java:

package com.soft9000;

public class MyProgram {

public static void CreateRecord() {


System.out.println("CreateRecord");
}

public static void DeleteRecord() {


System.out.println("DeleteRecord");
}

public static void ListRecords() {


System.out.println("ListRecords");
}

Lab Exercise Guide Page 35 of 80 Soft9000.com


Professional Java How To Java

39. The above code can also be found in the solutions folder in the archive file
mentioned at the start of this Exercise.

(end of lab)

Lab Exercise Guide Page 36 of 80 Soft9000.com


Professional Java How To Java

(Labs End)

Lab Exercise Guide Page 37 of 80 Soft9000.com


Professional Java How To Java

Appendix A: Questions & Activities

This section contains the answers to the Questions & Activates portion in the lectures
series.

Professional Java 1100: Answers & Solutions

The correct answer is 2.

Users who want to run our Java creations on their computer will need to install a Java
Runtime Environment (JRE.)

Lab Exercise Guide Page 38 of 80 Soft9000.com


Professional Java How To Java

The correct answer is 1.

Software developers who want to create & run Java programs only need to install the Java
Developers Toolkit (JDK.) The JDK automatically includes the instllation of a Java Runtime
Environment (JRE.)

Lab Exercise Guide Page 39 of 80 Soft9000.com


Professional Java How To Java

The program is missing a closing brace.

Lab Exercise Guide Page 40 of 80 Soft9000.com


Professional Java How To Java

The programs main method is not static.

Lab Exercise Guide Page 41 of 80 Soft9000.com


Professional Java How To Java

Professional Java 1200: Answers & Solutions

Problem 1: The result is not being returned.

Problem 2: Attempting to read data from any external resource can have unexpected
problems.

In the case of reading data from an InputStream, an IOException must be either thrown or
caught.

The following shows the completed code.

Lab Exercise Guide Page 42 of 80 Soft9000.com


Professional Java How To Java

Example of Exception catching:

public static int readInt(InputStream in) {


int result;
try {
result = in.read();
} catch (IOException ex) {
result = -1;
}
return result;
}

Example of Exception propagation:

public static int readInt(InputStream in) throws IOException {


int result = in.read();
return result;
}

NOTE: There are two primary advantages to catching & processing an expression within a
member function.

The first advantage to processing an exception locally is that the exception-processing logic
will not have to be re-written everywhere the routine is re-used.

Lab Exercise Guide Page 43 of 80 Soft9000.com


Professional Java How To Java

The second advantage is that - whenever an invalid value can be defined (in this case, a value
of -1,) a simple, single comparison to something like the INVALID_VALUE in the above
example saves time, thought, deliberation, as well as several lines of code.

In general a single comparison to an invalid value is usually far more preferable than
endlessly adding many lines of exception-handling code wherever a predefined member
function is re-used.

Lab Exercise Guide Page 44 of 80 Soft9000.com


Professional Java How To Java

After examining the entire program, the problem is that there is no way to know where reader
is. Without the type of fully-qualified path name discussed in the lecture, Java will not be able
to find the reader class.

Lab Exercise Guide Page 45 of 80 Soft9000.com


Professional Java How To Java

Problem 1: The keyword static is missing from main.

Problem 2: A closing brace is missing.

Problem 3: A closing semicolon (;) is missing from the second println.

Problem 4: The last println is clearly an attempt at string concatenation.

When performing a string concatination in Java a plus-sign (+), not an amperstand (&), is
required.

Lab Exercise Guide Page 46 of 80 Soft9000.com


Professional Java How To Java

The return type is String when a return type of int is required.

Lab Exercise Guide Page 47 of 80 Soft9000.com


Professional Java How To Java

Professional Java 2100: Answers & Solutions

The program is correct.

While many Java software developers will complain when curly-braces are missing or
misplaced, their omission and misplacement in this context is both permissible, as well
possible amongst all syntax derived from the C/C++ Programming Language.

Lab Exercise Guide Page 48 of 80 Soft9000.com


Professional Java How To Java

If phoneNumber remains null, the problem is that showSize will attempt to use a null member
variable. An attempt to access a member of any null object (such as the attempt to access
phoneNumber.length() in the above) will result in a run-time exception.

Lab Exercise Guide Page 49 of 80 Soft9000.com


Professional Java How To Java

To provide the answer to this activity, consider re-using the following:

Lab Exercise Guide Page 50 of 80 Soft9000.com


Professional Java How To Java

Please note that the package name for JavaOne need not be the same as show above.

Lab Exercise Guide Page 51 of 80 Soft9000.com


Professional Java How To Java

The solution to this Activity is to simply update the calculation in your solution to QA03 to
use the minus (-) rather than the plus (+) operator:

Lab Exercise Guide Page 52 of 80 Soft9000.com


Professional Java How To Java

Lab Exercise Guide Page 53 of 80 Soft9000.com


Professional Java How To Java

Professional Java 2200: Answers & Solutions

The correct answer is 1.

While a double can indeed be used to contain everything that can be expressed as a float, the
float is all that is required to sufficently represent all point-of-sale currency transactions.

Lab Exercise Guide Page 54 of 80 Soft9000.com


Professional Java How To Java

The correct answer is 2.

While a float can indeed be used to express everything at the point-of-sale, the double is a
better choice whenever an undefined set or series of mathematical calculations may be applied
to the value.

Lab Exercise Guide Page 55 of 80 Soft9000.com


Professional Java How To Java

When entering input from a keyboard, flowcharts often use the Manual Input symbol.

For the purposes of this training, a Process box may also be used in your design.

The Manual Input is highlighted in red on the following diagram:

Lab Exercise Guide Page 56 of 80 Soft9000.com


Professional Java How To Java

main

Prompt:
Enter
Number

Read
Integer
End

NO YES

Add Input Input Show


To Total is Results
Zero?

Figure 1: Adding Numeric Input (Flowchart)

Lab Exercise Guide Page 57 of 80 Soft9000.com


Professional Java How To Java

To read a number from the keyboard, we can use the readInt() from the lecture.

The following is the first half of JavaOne:

Lab Exercise Guide Page 58 of 80 Soft9000.com


Professional Java How To Java

Immediately after the above, our main() for JavaOne should look something like:

Lab Exercise Guide Page 59 of 80 Soft9000.com


Professional Java How To Java

Once run, a basic test case could look like the following:

A more complicated case:

The more complicated test verifies that all non-numeric input is ignored.

Lab Exercise Guide Page 60 of 80 Soft9000.com


Professional Java How To Java

Professional Java 3100: Answers & Solutions

Your solution might look something like the following:

Lab Exercise Guide Page 61 of 80 Soft9000.com


Professional Java How To Java

Your solution might look something like the following:

Lab Exercise Guide Page 62 of 80 Soft9000.com


Professional Java How To Java

The following flowchart captures the requirement:

Lab Exercise Guide Page 63 of 80 Soft9000.com


Professional Java How To Java

main

Prompt:
Enter
String

Read String

End

NO YES

Display Input
Each is
Character Empty?

Figure 2: Display Each Character (Flowchart)

Lab Exercise Guide Page 64 of 80 Soft9000.com


Professional Java How To Java

The following implementation includes the opportunity to create our own readString ability.

When reviewing the final solution for this activity, notice how casting each byte - by using
(char) in main - converts each integral-byte value into a human-displayable character.

Figure 3: Casting Byte to Char

Here is the complete code:

Lab Exercise Guide Page 65 of 80 Soft9000.com


Professional Java How To Java

Lab Exercise Guide Page 66 of 80 Soft9000.com


Professional Java How To Java

Professional Java 3200: Answers & Solutions

Like all diagram tyes, Flowcharts can depict either a high, or a low-level of detail.

The following is an example of a high-level depiction of the requirement:

Lab Exercise Guide Page 67 of 80 Soft9000.com


Professional Java How To Java

main

Prompt:
Enter
String

Read Number

End

NO YES

Display Is Zero
Even or Bad
Numbers # ?

Figure 4: Every Other Number (Flowchart Low Level Detail)

The following flowchart depicts the low-level detail for the requirement:

Lab Exercise Guide Page 68 of 80 Soft9000.com


Professional Java How To Java

main

DONE
Print Prompt:
Done?
Even Enter
Number Number

EVEN
ODD
Is Read #
Even? End

NOT ZERO EXIT

NOT DONE For Each # Is Zero Show


From 0 or Bad Results
(inclusive) # ?

Figure 5: Every Other Number (Flowchart Low Level Detail)

Lab Exercise Guide Page 69 of 80 Soft9000.com


Professional Java How To Java

Your implementation may look something like the following:

Lab Exercise Guide Page 70 of 80 Soft9000.com


Professional Java How To Java

Lab Exercise Guide Page 71 of 80 Soft9000.com


Professional Java How To Java

Your updated implementation may look something like the following:

Lab Exercise Guide Page 72 of 80 Soft9000.com


Professional Java How To Java

Lab Exercise Guide Page 73 of 80 Soft9000.com


Professional Java How To Java

Requires Java 1.7 or greater:

Lab Exercise Guide Page 74 of 80 Soft9000.com


Professional Java How To Java

Lab Exercise Guide Page 75 of 80 Soft9000.com


Professional Java How To Java

Appendix B: Setup Instructions


This section contains setup instruction for a Java Software Developer Environment.
Please note that tools & feature sets can change; these instructions were accurate at
the time of this writing.Setup Guide: Java Training

Objective
Install and test the tools required for this training. In order to download the installation
files, an Internet connection is required.

Overview
You will be performing the following tasks
1. Download & install an Oracle Developer Kit for Java (JDK)
2. Adding Oracles Java tools to the command prompt, as required
3. Download & install the Eclipse Integrated Development Environment (IDE)

Step by Step Guide

Solution File: none


Starter File: none

Step 01: Downloading Software Developer Support Files

This training was written to support the most recent version of both Java and Eclipse.
Moving forward, there should be no reason why the training will not work with the
most current release of these two products.

At the time of this writing, the software developer tools used by this training are free.

Minimum Requirements:
Java JDK: Version 1.7, or Java 7.
Eclipse IDE: Juno or Kepler.
Operating System:
Windows XP or greater
Ability to Install Software (Administrator Rights)
8 - 12 GB Available Hard Drive (HDD)
2 - 4 GB Programming Memory (RAM)

Lab Exercise Guide Page 76 of 80 Soft9000.com


Professional Java How To Java

Getting the installation files (tools):

1. The use of JDK 1.7 or greater is required.

a. We recommend using the Oracle SE JDK.

b. At the time of this writing, the JDK is available from


http://www.oracle.com/technetwork/java/javase/downloads/jdk7-
downloads-1880260.html

c. Alternatively, one may also go to http://www.oracle.com and search for


JDK 7

2. The use of Eclipse is supported.

a. We recommend using Eclipse Juno or greater. You will want to install the
Eclipse IDE for Java Developers.

b. Juno: http://eclipse.org/downloads/packages/release/juno/sr1

c. Kepler: http://eclipse.org/downloads/packages/release/kepler/r

d. Alternatively, one may also navigate to http://eclipse.org to press the


Download Eclipse Button.

3. Once both Eclipse and the Oracle JDK have been downloaded, proceed to the
next step.

4. NOTE: From company policies to anti-virus settings & administrator privilges,

Lab Exercise Guide Page 77 of 80 Soft9000.com


Professional Java How To Java

there can be many settings that may manage where files may be downloaded on
your computer.

5. If you encounter problems downloading the above files, then:

a. If your are using a company computer:

i. You might wish to discuss where, when, and if (!) you are able to
download and install Java on your computer.

ii. Try saving downloaded files to removable media (like a USB Storage
Device or Thumb Dirve.) You should have at least 8 GB free on your
removable device.

b. If you are using a Personal Computer:

i. Be certain you are logged-in as an Administrator.

ii. Be sure you have enough space for the download & installation process.

Step 02: Installing The JDK

In order for Eclipse to find the software developer tools, the SDK must be installed
before the IDE.

6. Locate & click-on the downloaded JDK to start the installation process.

7. Follow the instruction so as to install the JDK.

8. Make a note of where the JDK is being installed on your computer!

9. Once the JDK had been installed, reboot your computer.

10. Once your computer has restarted, open a Command Prompt.

a. Click on Start so as to select All Programs to open Accessories.

Lab Exercise Guide Page 78 of 80 Soft9000.com


Professional Java How To Java

b. The Command Prompt will be located within the Accessories Folder.

11. Operating at the command prompt, type in java -version:

12. Verify that a minimum version of Java 1.7.x has been installed. Version 1.7 or
created is required by this training.

a. If the java command is not recognized, then Oracle Java has not been
properly installed.

b. If the version of Java is not 1.7 or greater and the recommended version
of Oracle Java has been installed, note that in order to complete any
command-line exercises in this training that you will need to either:

i. Remove the older version(s) of Java or

ii. Update your system path so as to use the recommended version of


Java

13. Proceed to the next step.

Lab Exercise Guide Page 79 of 80 Soft9000.com


Professional Java How To Java

Step 03: Installing Eclipse

The Eclipse IDE is distributed either within a ZIP file or (On Microsoft Windows) as an
.EXE installer file.

14. If you have downloaded a Microsoft Windows Installer, click on the .EXE file.
Follow the instructions to complete the installation process.

15. If you have a .ZIP file, clicking on the file will open the archive. To install Eclipse,
merely drag-and-drop the enclosed eclipse folder to your desktop.

16. Once Eclipse has been installed, clicking on the eclipse icon located directly
underneath the eclipse folder will start the Eclipse IDE.

Step 04: Download Training Support Files

Please refer to the video section on YouTube to locate and download the associated
training exercise solution files, as desired.

(end of setup)

Lab Exercise Guide Page 80 of 80 Soft9000.com

S-ar putea să vă placă și