chapter 3: program control statements. input characters from the keyboard know the complete form...
TRANSCRIPT
JAVA: A BEGINNER’S GUIDEChapter 3: Program Control Statements
2
KEY SKILLS AND CONCEPTS
Input characters from the keyboard Know the complete form of the if
statement Use the switch statement Know the complete form of the for loop Use the while loop Use the do-while loop Use break to exit a loop
3
KEY SKILLS AND CONCEPTS
Use break as a form of goto Apply continue Nest loops
4
INPUT CHARACTERS FROM THE KEYBOARD Interactive programs require a way for
the user to communicate with the program.
Most user interactive applications are graphical based (GUI – Graphical User Interface).
You can also create console-based (non-GUI) applications.
Java provides several classes to read console-based data.
5
INPUT CHARACTERS FROM THE KEYBOARD The System class:
System class provides facilities for standard input (System.in), standard output (System.out), and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.
It is always available (imported) to programs.
6
INPUT CHARACTERS FROM THE KEYBOARD System.in provides an input stream of
bytes. The read() method reads a byte or
bytes of data into a byte variable or byte array.
Not very practicable for user interaction.
7
INPUT CHARACTERS FROM THE KEYBOARD Java has classes that provides for more
flexible means of entering data: Scanner BufferedReader Console
Requires an import statement (gives access to the classes) Scanner: import java.util.Scanner; BufferedReader/Console: import java.io.*;
8
INPUT CHARACTERS FROM THE KEYBOARD Scanner Class Must create an instance of the class:
Scanner keyboard = new Scanner(System.in);
Scanner is the class keyboard is the name you give to the instance
of the class. = new Scanner(System.in) assigns the new
instance to the keyboard object.
9
INPUT CHARACTERS FROM THE KEYBOARD Scanner methods read specific data types;
nextByte() – reads byte data type. nextShort() – reads short data type nextInt() – reads int data type nextLong() reads long data type nextFloat() read float data type nextDouble() reads double data type nextBoolean() reads boolean data type next() reads a string up to a separator (may be a
space) nextLine() reads a string through end of line
10
INPUT CHARACTERS FROM THE KEYBOARD Scanner class limitations:
User must enter the correct type of data Strings can cause some problems when using
nextLine() versus next() methods No method to read char data type
next().charAt(0) reads a single character type
Scanner class benefits: Easy to implement Provides specific methods for specific data
types
11
INPUT CHARACTERS FROM THE KEYBOARD
// Declare varaibles. String aString; char aChar; byte aByte; short aShort; int anInt; long aLong; float aFloat; double aDouble; boolean aBoolean; // Create an instance of the scanner class.Scanner console = new Scanner(System.in); // Read string data.System.out.println("Enter a string: ");aString = console.next(); // Read a char data type.System.out.println("Enter a character: ");aChar = console.next().charAt(0);
// Read a 16 bit integer (short) System.out.println("Enter a 16 bit integer (short): "); aShort = console.nextShort(); // Read a 32 bit integer (int). System.out.println("Enter a 32 bit integer (int): "); anInt = console.nextInt(); // Read 64 bit integer (long) System.out.print("Enter a 64 bit integer(long): "); aLong = console.nextLong(); // Read a 32 bit floating point value (float) System.out.println("Enter a 32 bit floating point value (float): "); aFloat = console.nextFloat(); // Read a 64 bit floating point value (double) System.out.println("Enter a 64 bit floating point value (double): "); aDouble = console.nextDouble(); // Read a boolean value System.out.println("Enter a boolean value (true/false): "); aBoolean = console.nextBoolean();
// Read an 8 bit integer (byte)System.out.println("Enter an 8 bit integer (byte): ");aByte = console.nextByte();
Scanner Class Example:
12
INPUT CHARACTERS FROM THE KEYBOARD BufferedReader class Must create an instance of the class:
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
BufferedReader is the class keyboard is the name you give to the instance of
the class. = new BufferedtReader(new
InputStreamReader(System.in)) assigns the new instance to the keyboard object.
13
INPUT CHARACTERS FROM THE KEYBOARD BufferedReader methods
read() – reads a single character readLine() – reads the entire line (string)
All data from the readLine() method is string
Data must be converted to its data type before it can be used.
14
INPUT CHARACTERS FROM THE KEYBOARD
// Create an instance of a buffered reader.BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
// Read string data.System.out.println("Enter a string: ");aString = keyboard.readLine();
// Read a char data type.System.out.println("Enter a character: ");aChar = keyboard.readLine().charAt(0);
// Read an 8 bit integer (byte)System.out.println("Enter an 8 bit integer (byte): ");aByte = Byte.parseByte(keyboard.readLine());
// Read a 16 bit integer (short)System.out.println("Enter a 16 bit integer (short): ");aShort = Short.parseShort(keyboard.readLine());
// Read a 32 bit integer (int).System.out.println("Enter a 32 bit integer (int): ");anInt = Integer.parseInt(keyboard.readLine());
// Read 64 bit integer (long)System.out.print("Enter a 64 bit integer(long): ");aLong = Long.parseLong(keyboard.readLine());
// Read a 32 bit floating point value (float)System.out.println("Enter a 32 bit floating point value (float): ");aFloat = Float.parseFloat(keyboard.readLine());
// Read a 64 bit floating point value (double)System.out.println("Enter a 64 bit floating point value (double): ");aDouble = Double.parseDouble(keyboard.readLine());
// Read a boolean valueSystem.out.println("Enter a boolean value (true/false): ");aBoolean = Boolean.parseBoolean(keyboard.readLine());
BufferedReader Example:
15
INPUT CHARACTERS FROM THE KEYBOARD Console class Must create an instance of the Console class
Console keyboard = System.console(); Console is the class keyboard is the name you give to the instance of the
class. = System.console() is assigned to the keyboard object.
Note: the keyword new is not used.
May not work under all conditions. Whether a virtual machine has a console is dependent upon the underlying
platform and also upon the manner in which the virtual machine is invoked.
16
INPUT CHARACTERS FROM THE KEYBOARD Console class methods
readLine() – reads a line of text (string). readPassword() – reads a line of text but
does not echo it back to the monitor. All data from the readLine() and
readPassword() methods are string Data must be converted to its data
type before it can be used.
17
INPUT CHARACTERS FROM THE KEYBOARD
// Read a 32 bit integer (int).System.out.println("Enter a 32 bit integer (int): ");anInt = Integer.parseInt(con.readLine());
// Read 64 bit integer (long)System.out.println("Enter a 64 bit integer(long): ");aLong = Long.parseLong(keyboard.readLine());
// Read a 32 bit floating point value (float)System.out.println("Enter a 32 bit floating point value (float): ");aFloat = Float.parseFloat(con.readLine());
// Read a 64 bit floating point value (double)System.out.println("Enter a 64 bit floating point value (double): ");aDouble = Double.parseDouble(con.readLine());
// Read a boolean valueSystem.out.println("Enter a boolean value (true/false): ");aBoolean = Boolean.parseBoolean(con.readLine());
// Create a console objectConsole con = System.console(); // Read string data.System.out.println("Enter a string: ");aString = con.readLine();
// Read a char data type.System.out.println("Enter a character: ");aChar = con.readLine().charAt(0);
// Read an 8 bit integer (byte)System.out.println("Enter an 8 bit integer (byte): ");aByte = Byte.parseByte(con.readLine());
// Read a 16 bit integer (short)System.out.println("Enter a 16 bit integer (short): ");aShort = Short.parseShort(con.readLine());
Console Class example:
18
INPUT CHARACTERS FROM THE KEYBOARD Regardless of which class you use,
errors may occur. You should always precede any input
statement with a prompt. Tell the user what to enter May tell the user what is valid
System.out.println("Enter a grade (A, B, C, D, or F): ");
19
THE IF STATEMENT
Used to take alternate courses of action base on data (condition).
The condition is a relational statement that evaluates to true or false.
if (condition){ Statement(s); // if condition is true}else // if condition is false{ Statement(s); // if condition is false}
Remember: Curly braces indicate a block of code. No semicolon follows the if (condition) or else
statements.
20
IF STATEMENT: JAVA VS PSEUDOCODEJAVAif (condition){ statement(s);}else { statement(s);}
Pseudocodeif ( condition)
statement(s)else
statements(s)endif
Note: For java, there is no semicolon following: if (condition) or else.
21
THE IF STATEMENT
Single alternative if statement Only true component
if (condition){ Statement(s) // if condition is true}
22
THE IF STATEMENT
Dual alternative if statement Has both true and false components
if (condition){ Statement(s); // if the condition is true}else // Begins the false part{ Statement(s); // if the condition is false}
Note: If only a single statement follows the if or else statement, it is not necessary to use a set of curly braces. However, it is highly recommended.
23
CONDITIONAL OPERATORS
Condition: (value1 operator value2) Must evaluate to true or false May be a single boolean value
Operator
Meaning
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
24
CONDITIONAL EXPRESSIONS
Conditional Expression
Meaning Result
(i == 10) is i (10) equal to 10 true
(i > y) is i (10) greater than 7 false
(y >= x) is y (7) greater than or equal to x (14)
false
(x < 8) is x (14) less than 8 false
(i <= x) is i (10) less than or equal to x (14) true
(x != y) is x (14) not equal to y (7) true
Given the following variables:int i = 10;int x = 14;int y = 7;
Note: Any value, variable or literal, can be on either side of the conditional operator.
25
IF STATEMENT EXAMPLE
Given the following data:int quantityOrdered = 10;int quantityOnHand = 9;int quantityShipped;
if (quantityOrdered <= quantityOnHand){
quantityShipped = quantityOrdered;quantityOnHand -= quantityShipped;
}else{
quantityShipped = quantityOnHand;quantityOnHand = 0;
}
26
NESTED IFS
The body of an if statement can contain any executable statements, including other if statements.
Applies to both if and else sections. There is no limit to the number of nesting levels.if (condition){
statement(s)if (condition) // will only execute if the first if is true{
statement(s)}statement(s)
}
27
THE IF-ELSE-IF LADDER
Based on a nested if.if (condition) statement;else if (condition) statement;else if (condition) statement;…else statement; Each if condition can only be executed if the
preceding conditions were all false. Note: you can omit curly braces if your code
block consists of only a single statement.
28
NESTED IF STATEMENT
if (condition1)if (condition2)
if (condition3)if (condition4)
statement; statement will only execute if all conditions above
are true.
29
NESTED IF STATEMENT – MULTIPLE STATEMENTS
if (condition1) {
statement(s);if (condition2) {
statement(s);if (condition3) {
statement(s);}else {
statements(s);}
}statement(s);
}
Curly braces must be used in pairs.
Indenting increases readability.
30
COMPOUND CONDITIONS
Can simplify your code by testing multiple values.
The resultant condition must still evaluate to true/false.
Each condition must be in the form of: value1 operator value2
Can use AND, OR, XOR logic
31
COMPOUND CONDTIONSLogic Conditio
n1Condition2
Result
AND (&& or &)
true true true
AND (&& or &)
true false false
AND (&& or &)
false true false
AND (&& or &)
false false false
OR (|| or |) true true true
OR (|| or |) true false true
OR (|| or |) false true true
OR (|| or |) false false false
When using compound ANDs, all conditions must be true for the resultant condition to be true. If any are false, then the resultant condition is false.
When using compound ORs, any condition can be true for the resultant condition to be true. In order for the resultant condition to be false, all conditions must be false.
32
CONDITIONAL VERSUS LOGICAL OPERATIONS
Conditional Operations (Short circuit) && = Conditional and || = Conditional or
Saves computing time by not continuing to execute conditions once a resultant determination can be made.
Best for most compound operations Logical Operations
& = Logical and | = Logical or
Each condition is executed regardless of the eventual outcome.
Best if a condition(s) contains an assignment statement.
33
COMPOUND CONDITIONS
Logic Condition 1 Condition 2 Condition 3 Result
XOR (^) true true true true
XOR (^) true true false false
XOR (^) true false true false
XOR (^) true false false true
XOR (^) false true true false
XOR (^) false true false true
XOR (^) false false true true
XOR (^) false false false false
Exclusive OR:
34
COMPOUND CONDITION EXAMPLE
int age;char gender;
if (gender == 'M' && age >= 25)System.out.println("You are eligible for a discount.");
else if (gender == 'F' && age >= 21)System.out.println("You are eligible for a discount.");
This can be rewritten as:
if ((gender == 'M' && age >= 25) || (gender == 'F' && age >= 21))
System.out.println("You are eligible for a discount.");
35
THE SWITCH STATEMENT
Can be substituted for a nested if statement providing you are testing the same variable/expression to a constant value.
Format: switch (expression){
case constant1:statement(s)break;case constant2:statement(s)break;…default:statement(s)
}
36
THE SWITCH STATEMENT
expression – variable or expression that will be compared to a constant literal value.
Can only evaluate integer types (byte, short, int, char) and strings (JDK 7 and later).
No duplicate case values can be specified. break statement is optional.
break – exits the switch statement no break – each case is evaluated until a break
statement is found or the end of the switch statement is reached.
37
THE SWITCH STATEMENT
Empty case statements are an implied Or.switch (i){
case 1:case 2:case 3: System.out.println("Value is 1, 2, or 3");
break;case 4: System.out.println("Value is 4");
break;}
Switch statements can be nested.
38
SWITCH EXAMPLE
char finalGrade = ‘C’;switch (finalGrade){
case ‘A’: System.out.println("You made an A for the course!");break;
case ‘B’: System.out.println("You made a B for the course!");break;
case ‘C’: System.out.println("You made a C for the course!");break;
case ‘D’: System.out.println("You made a D for the course!");break;
case ‘F’: System.out.println("You made an F for the course!");break;
default: "System.out.println("Your grade has not been determined.");}
39
SWITCH EXAMPLE
String state = "AZ";switch (state){
case "AZ": case "NM": case "UT": case "CO": System.out.println("One of the 4 corners states.");break;
case "DE": case "PA": case "NJ": case "GA" case "CT": case "MA":case "MD": case "SC": case "NH": case "VA": case "NY":case "NC": case "RI":
System.out.println("One of the original 13 colonies."):break;
}
40
LOOPS
Repeats instructions for multiple sets of data.
Several loop structures while for do…while
Two general categories Pre-test loops Post-test loops
41
THE FOR LOOP
Shorthand version of a while loop. Format:
Pre-test loop: Condition is tested at the beginning of the loop. Executes as long as the condition is true Loop may not execute at all.
for(initialization; condition; iteration){
Statement(s)}
42
THE FOR LOOP
for(initialization; condition; iteration) Initialization – Usually an assignment statement
Variable is called the loop control variable Condition – Conditional test to determine if the
loops continues to execute Usually involves the loop control variable Like all conditions, must evaluate to true or false Loop continues to execute as long as the condition is
true Iteration – statement that modifies the loop
control variable
43
THE FOR LOOP
x = 0
x < 10
System.out.println(“This is iteration
# “ + x);x++
true
false
Pre-test loop structure.
44
THE FOR LOOP
Example:
x is the loop control variable. x is only available within the loop. x++ is incremented on each iteration.
for(int x = 0; x < 10; x++){
System.out.println(“This is iteration # “ + x);}
45
VARIATIONS OF THE FOR LOOP
Each component (initialization, condition, iteration) are optional If you leave a component out, you are responsible for
managing the loop yourself If a component is missing, you must still provide the
separating semicolon. You can have multiple initialization statements You can have compound conditions You can have multiple iteration statements A for loop with no components is an infinite
loop.
46
LOOPS WITH NO BODY
May be useful on certain occasions.
Adding a semicolon after the for statement is often a mistake. A diagnostic message may not be issued.
int i;int sum = 0;for(i = 1; i <= 5; sum += i++);
47
THE WHILE LOOP
Format:
Pre-test loop. Executes as long as the condition is true. Initialization is typically before the while
statement. Iteration occurs typically inside the loop body.
while (condition){
Statement(s)}
48
THE WHILE LOOP
Example:
Loop will make 5 iterations
int count = 0while(count < 10){
System.out.println("Count is: " + count);count += 2;
}
Program output:Count is: 0Count is: 2Count is: 4Count is: 6Count is: 8
49
THE DO-WHILE LOOP
Post-test loop structure Condition is tested at the end of the loop. Will always have 1 iteration regardless of
the loop control value. Good for menus and data entry routines.
Format:do{
Statements(s)} while (condition);
50
THE DO-WHILE LOOP
x = 0
x < 10
System.out.println(“This is iteration
# “ + x);x++
true
false
Post-test loop structure.
51
THE DO-WHILE LOOPchar grade;do{
System.out.println("Enter a letter grade (A, B, C, D, F): ");grade = (char) System.in.read(); // System.in.read() returns
an int type.} while (! (grade =='A' || grade == 'B' || grade == 'C' || grade == 'D' || grade = 'F'));
Note the negation operator !. Remember items inside parenthesis are evaluated first. If grade is one of the valid values, then the condition inside the parenthesis it true. The ! reverses the test.
52
BREAK AND CONTINUE
break; Forces an immediate exit from the loop.
continue; Forces the next iteration of the loop to execute. Any statements after the continue; statement
will not be executed.
Pay close attention to loop control variables when using continue;.
53
USING CONTINUE WITH A FOR LOOP
When a continue statement is encountered within a for loop, the iteration part of the statement is still executed.
This is not true when a continue statement is encountered for a while or do-while loop.
54
COMMON LOOPING PROBLEMS
Loop executes one to many or one to few times. Be sure you know your starting and ending points.
Programmer forgets to initialize the loop control variable.
Programmer forgets to update the loop control variable.
Programmer using an incorrect conditional test. <= instead of < or < instead of <= >= instead of > or > instead of >=
Be careful when just testing for equality (==).
55
NESTED LOOPS
As with if statements, loops can be nested.
No limit to the number of nesting levels. I would never go more the 3 or 4 deep
unless you have a really good reason. You can mix loop structures
For example; a while loop inside of a for loop inside of a do-while loop.
56
TESTING YOUR LOOPS
When testing loops with large numbers of iterations, use a small number representative of the data; Example: use 10 iterations instead of 100
or 1000 Be sure you get the correct number of
iterations. Avoid the 1 off error.
Test all possibilities!