Sunday, May 17, 2009

Tutorial 3 - Control Flow

NOTE : -  THIS IS NOT THE ORIGINAL CONTENT

Tutorial 3 - Control Flow

This tutorial on basic Java control flow assumes some introductory programming experience in another language.

Conditional Statements

Conditional statements execute a block or set of other statements only if certain conditions are met. The condition is always enclosed in round brackets. The statements to be performed if the condition is true are enclosed in curly brackets. For example:

if (value > 5) {x=7;}

Note: If the block (ie. curly brackets) contains only one statement, you may leave the brackets off. But this is not good programming practice. The curly brackets make the code more consistent and easier to read.

Occasionally you may want to perform some actions for the false outcome of a condition as well. The else keyword is used to separate branches.

if (name == "Fred") {x=4;}   else {x=20;};

Note: When the conditional if statement is used only to make an assignment to one variable, you can use the terse Cconditional operator. A simple example is:

x=(name == "Fred") ? 4 : 20;

Loops

For statements allow a set of statements to be repeated or looped through a fixed number of times. The round bracket contains initializer(s) ; conditional test ; incrementer(s). If more than one initializer or incrementer is used they are separated with commas. The test condition is checked prior to executing the block. The incrementing is doneafter executing the block. For example to output #1 #2 etc.(or #5 #4 etc.) on separate rows you could write:

for (int i=1;i<=5;i++) {document.writeln("#"+i);}; for (int i=5;i>=1;i--) {document.writeln("#"+i);};

Note: A special case of the for loop is the infinite loop for (;;){...}. This could be used with appropriate 'breakout' logic where a continuous operation was needed.

Caution: For loops can be written in ways that violate structured programming principles by allowing counter variables to be used outside of the scope of the loop block if they are defined outside the loop. Avoid the looseness of the language by always localizing the loop variable.

The enhanced for statement allows iteration over a full set of items or objects. For example:

int[] squares={0,1,4,9,16,25}; for (int square : squares) {...;} // is equivalent to for (int 1;i

While statements allow a set of statements to be repeated or looped until a certain condition is met. The test condition is checked prior to executing the block. For example to output #1 #2 etc. on separate rows you could write:

int i=0; while (i<=5) {    document.writeln("#"+i); i++;    };

Do While statements allow a set of statements to be repeated or looped until a certain condition is met. The test condition is checked after executing the block. For example to output #1 #2 etc. on separate rows you could write:

int i=1; do {    document.writeln("#"+i); i++;    } while (i<=5);

The Switch Statement

Switch (or case) statements are used to select which statements are to be executed depending on a variable's value matching a label. default is used for the else situation. Note that the selection variable can only be int or chardatatype.

switch (selection)    {    case '1': System.out.println("You typed a 1"); break;    case '2': System.out.println("You typed a 2"); break;    default : System.out.println("Oops!, that was an invalid entry.");    };

Continue, Break and Return

Continue statements are used in looping statements to force another iteration of the loop before reaching the end of the current one. Most often continue is used as part of a conditional statement that only happens in certain cases. The following is a trivial example.

int x=0; while (x <>

Break statements are used in looping and 'switch' statements to force an abrupt termination or exit from the loop or switch. In the following example the loop is never completed. Once again the normal use of break is as part of a conditional statement.

int x=0; while (x <>

Return statements are used to force a quick exit from a method. They are also used to pass values back from methods.

Command Line Arguments

Command line arguments are accessible through the args[] array (assuming that args is the name used in the specification for main [Note: args[] is a Java coding convention!]). The array does not include the interpreter javacommand or the class name and the count starts at 0. Each argument is passed as a string but may be converted as in the following:

int w=Integer.parseInt(args[0]); // or sometimes you want the argument to be a character type char s=args[1].charAt(0); // uses first letter of argument only

Note: The methods parseInt() and charAt() are referenced in the type wrappers and string class topics.

Warning: Double quote marks are consumed by the command line parser and are not passed on to the args[] array!

The number of arguments passed in from the command line can be determined by using the args.length property. This is important when testing for required arguments, when there is a variable number of arguments or when there is an unpredictable number of arguments (eg. the file glob expansions (* and ?) in batch operation).

Command line options are arguments with a prefix of - (dash) and is UNIX-centric. They normally precede pathnames in the command line. Options are normally a single character but sometimes are a number or followed by a number. Examples of command line options are:

pr -d *.htm  ; print double spacing lines head -10 *.htm ; show first 10 lines head -c 10 *.htm ; show first 10 characters

Command line switches are arguments with a prefix of / (slash) and is msDOS-centric. They normally toggle boolean flags but can be found in many variations such as a following argument qualifier or a parsing situation. Depending on programmer, they may have to precede or follow file arguments.Examples are:

find /p fred *.htm  ;page pause requested progname /help ;help or man page requested format /head=4. *.htm ;include 4 lines of header space print -lines 45 *.htm ;print first 45 lines of file(s)

Note: I personally prefer switches to options but YMMV! Try to develop a standard argument option|switch handling routine that is as user tolerant as possible regarding switches and filenames. The routine should identify switches by the prefix / and act appropriately. Routines that are accessing filenames from the args[] array should skip switches (as identified with the / prefix). You may want to view the one used in include.java.

Project: Basic Problems

This project is a series of simple problems that use arraysloopscommand line arguments for input and a simpleSystem.out.println(string); statement for output.

Problem 1: Write a program that allows you to create an integer array of 18 elements with the following values:int A[]={3,2,4,5,6,4,5,7,3,2,3,4,7,1,2,0,0,0}. The program computes the sum of element 0 to 14 and stores it at element 15, computes the average and stores it at element 16 and identifies the smallest value from the array and stores it at element 17.

Problem 2: Write a program that accepts two numbers from the command line and prints them out. Then use a for loop to print the next 13 numbers in the sequence where each number is the sum of the previous two. For example:

input> java prob2 1 3 output> 1 3 4 7 11 18 29 47 76 123 322 521 843 1364

Problem 3: Write a program that accepts two numbers in the range 1 to 40 from the command line. It then compares these numbers against a single dimension array of five integer elements ranging in value from 1 to 40. The program displays the message BINGO if the two inputted values are found in the array element. For example:

input>java prob3 3 29 output>Your first number was 3        Your second number was 29        Its Bingo! // this message if 3 and 29 is found in the array        Bokya!     // this message if 3 and 29 is not found in the array        The array was 7 25 5 19 30

An extension for problem 3 would be to generate the array of five unique integers using random numbers

Problem 4: Create a program using loops to form this figure:

         n=3                n=4           *                  *          *$*                *$*         *$*$*              *$*$*          *$*              *$*$*$*           *                *$*$*                             *$*                              *
 

Project: Metric Converter

This project tests your knowledge of syntax without getting too involved in the complexities of object manipulation or a user interface. A toy metric converter should be just about right as it allows three basic stages of application development; IPO, branching, and switch selection.

The First Stage [Input - Process - Output]

The goal of the first stage of this project is to input from the command line a temperature given in degrees Fahrenheit (a geezer's unit), calculate the value in Celsius (the modern way) and then display the answer. This will test your ability to get some input, do a math process and finally display the output. It also gives some practice working with the development environment and doing compilations.

The basic input procedure will be to get the Fahrenheit reading from the command line using the methodInteger.parseInt(args[0]) which returns an integer from the first argument on the command line.

The math processing part is really easy. Celsius, a scientist, used water as his gauge so freezing was 0 and boiling was 100. Fahrenheit, an engineer used a more commonly available liquid, alcohol for his range :-). As alcohol freezes at lower temperatures, that is why the 32° difference. Because of the difference in range from freezing to boiling of the two liquids the ratio of size of the units turns out to be 100 to 180 or 5 to 9. This is the basic principle for the formuladeg_C=((deg_F-32) * 5)/9. Since division may produce a real number with a decimal value, you should cast the input number into a double and work with double precision floating point numbers (aka real numbers). Caution: Be sure to rewrite the formula with decimal numbers!

Once the answer is calculated, it can be output to your display by using the method System.out.println(deg_C)

Note: This program must be run from the command line with an integer following the program name. No error checking has been done yet!

Second Stage [Branching]

The second stage is to modify the application so that the conversion can be made in either direction. This will require a logical branch based on some additional input. Let's say the input has to look like 40 F or 10 C

    char units=args[1].charAt(0);     units=Character.toUpperCase(units);     if (units == 'F')     {     //do F --> C conversion     }     else     {     //do C --> F conversion     }

Also the command line should be checked to make sure that the number of arguments is correct (which we failed to do in stage one). A simple error message can be printed after checking the count such as:

    if (args.length != 2)     {       System.out.println ("Usage: Metric_2 ## F|C");       return;     }

Third Stage [Switches]

The third stage is to use the units argument to select an appropriate conversion routine (temperature, mass, distance, etc.) and switch to routines accordingly. For our program just add routines to convert lbs to kilograms and kg to lbs. This stage maxes out the limits of programming in the small. In later tutorials you will learn how to use custom objects to encapsulate data and procedures as well as how to use GUI objects to allow for interactive input.

switch (units) {   case 'F': { /* conversion routine */ } ; break;   case 'C': { /* conversion routine */ } ; break;   case 'L': { /* conversion routine */ } ; break;   case 'K': { /* conversion routine */ } ; break;   default : System.out.println("Oops! I do not understand the units..."); }

BIBLIOGRAPHY / REFERENCE : -

FOR REFERENCE....PLEASE VISIT :


P.S. : THIS CONTENT IS TAKEN FROM THE ABOVE MENTIONED SITE

1 comment:

  1. thanx a tone dude for this great post...
    u did a great job!!!
    u rock!!!!
    keep posting!!!!

    3 cheers for you..

    hip hip hurray !!!!
    hip hip hurray !!!!
    hip hip hurray !!!!

    ReplyDelete