Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
155 views

Lecture 2 Loops

The document discusses Java's printf formatting method and provides examples of how to format different data types when outputting to the console. It shows how to format integers, floating point numbers, dates, and other data types by controlling padding, number of decimal places, alignment, and other display properties. The examples demonstrate how to format numbers with commas, prefixes, minimum widths, and locale-specific number formats like those in France.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
155 views

Lecture 2 Loops

The document discusses Java's printf formatting method and provides examples of how to format different data types when outputting to the console. It shows how to format integers, floating point numbers, dates, and other data types by controlling padding, number of decimal places, alignment, and other display properties. The examples demonstrate how to format numbers with commas, prefixes, minimum widths, and locale-specific number formats like those in France.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 83

DECISON MAKING AND LOOPS

Lecture 2_a-2_b
System.out.printf
import java.util.Calendar;
import java.util.Locale;
public class TestFormat {
public static void main(String[] args) {
long n = 461012;
System.out.format("%d%n", n); // --> "461012"
System.out.format("%08d%n", n); // --> "00461012"
System.out.format("%+8d%n", n); // --> " +461012“
System.out.format("%,8d%n", n); // --> " 461,012“
System.out.format("%+,8d%n%n", n); // --> "+461,012"
double pi = Math.PI;
System.out.format("%f%n", pi); // --> "3.141593“
System.out.format("%.3f%n", pi); // --> "3.142"
System.out.format("%10.3f%n", pi); // --> " 3.142"
System.out.format("%-10.3f%n", pi); // --> "3.142"
System.out.format(Locale.FRANCE, "%-10.4f%n%n", pi); // --> "3,1416"
Calendar c = Calendar.getInstance();
System.out.format("%tB %te, %tY%n", c, c, c); // --> "May 29, 2006"
System.out.format("%tl:%tM %tp%n", c, c, c); // --> "2:34 am“
System.out.format("%tD%n", c); // --> "05/29/06" }
}
https://www.cs.colostate.edu/~cs160/.Summer16/resources/Java_printf_method_quick_reference.pdf
WHAT HAPPENS WHEN WE RUN A CLASS…
 When JVM starts running, it finds the selected class. Then it
starts looking for special method

Public static void main (String[ ] args) {


//your code here
}

 Every java application has to have at least one class

 One main method per application(package/project)


RUN A CLASS.. MEANS
 Running program means

 Run the file with the same class name

 Run the main method of that class

 No matter how long your program is (no matter how many


classes a single file has ) there has to be a main method to get
some results
SYNTAX OF A CLASS
Access specifier class classname{
Type instance_variable 1;
Data members

Type instance_variableN; (Things an object knows)

//METHODS
Type methodname1 ( parameter_list ){
//body
} Member Methods
… (Things an object does)
Type methodnameN ( parameter_list ){
// body
}
}
EXAMPLE
public class Rectangle {
//two variables
public int breadth;
public int length;

//two methods
public void setLength(int newValue){
length =newValue;
}
public void setBreadth(int newValue){
Breadth= newValue;
}
}
RULES OF CLASS

 A class can only be public or default


 It can be abstract, final or concrete(normal class)
 It must have class keyword
 It can extend(i.e. inherit) one parent class.
 It can implement any number of comma-separated interfaces
 The class variables and methods are declared within a set of curly braces{}
 Each .java source file may contain only one public class. A source file may
contain any number of default visible classes
 Finally, the source file name must match the public class name and it must
have .java extension
Variable and constants
DECLARING VARIABLES: SYNTAX
 Format:
<type of information> <name of variable>;

 Example:
char myFirstInitial;

 Variables can be initialized (set to a starting value) as they’re


declared:
char myFirstInitial = ‘j’;
int age = 30;
SOME BUILT-IN TYPES OF VARIABLES IN JAVA
Type Casting Variables
public class TypeCastingExample {
public static void main(String[] args){
 output:
int n=54; 2
float f=2.5f;
double d=5.1234567890; 5
boolean b=true;
byte byt=12; 12
System.out.println((int)f);
5.123457
System.out.println((int)d); 5
System.out.println((int)byt);
12.0
System.out.println((float)d);
System.out.println((byte)d);

System.out.println((double)byt);
}
}
JAVA CONSTANTS
Reminder: Constants are like variables in that they have a
name and store a certain type of information but unlike
variables they CANNOT change.

Format:
final <constant type> <CONSTANT NAME> = <value>;

Example:
final int SIZE = 100;
Why Use Constants?
 It can make your program easier to maintain (update with
changes).

 If the constant is referred to several times throughout the


program, changing the value of the constant once will
change it throughout the program.

 E.g.Value of PI
VARIABLE NAMING CONVENTIONS IN
JAVA
 Compiler requirements
 Can’t be a keyword nor can the names of the special constants: true, false or null
be used
 Can be any combination of letters, numbers, underscore or dollar sign (first
character must be a letter or underscore)
 Common stylistic conventions
 The name should describe the purpose of the variable
 Avoid using the dollar sign
 With single word variable names, all characters are lower case
e.g., double grades;
 Multiple words are separated by capitalizing the first letter of each word except
for the first word
e.g., String firstName = “James”;
JAVA KEYWORDS

abstract boolean break byte case catch char

class const continue default do double else

extends final finally float for goto if

implement
import instanceof int interface long native
s

new package private protected public return short

static super switch synchronized this throw throws

transient try void volatile while


JAVA OPERATOR PRECEDENCE
COMMON JAVA OPERATORS /
OPERATOR PRECEDENCE
Precedence Operator Description Associativity
level

1 expression++ Post-increment Right to left


expression-- Post-decrement

2 ++expression Pre-increment Right to left


--expression Pre-decrement
+ Unary plus
- Unary minus
! Logical negation
~ Bitwise complement
(type) Cast
COMMON JAVA OPERATORS /
OPERATOR PRECEDENCE
Precedence Operator Description Associativity
level

3 * Multiplication Left to right


/ Division
% Remainder/modulus
4 + Addition or String Left to right
concatenation
Bitwise shift Operators
Subtraction
- Assume int A = 60 i.e. 111100 then
5 << A <<
Left bitwise 2 will give 240 Left
shift 1111 to 0000
right
>> A >>2
Right bitwise will give15 which is 1111
shift
A >>>2 will give15 which is 0000 1111
COMMON JAVA OPERATORS /
OPERATOR PRECEDENCE
Precedence Operator Description Associativity
level

6 < Less than Left to right


<= Less than, equal to
Relational
Operators > Greater than
>= Bit Wise
Greater Operators
than, equal to
7 ==
a = 0011 1100
Equal to Left to right
b = 0000 1101
!= Not equal to
-----------------
8 & Bitwise AND Left to right
a&b = 0000 1100
a|b = 0011 1101
9 ^ Bitwise
a^bexclusive
= 0011 OR 0001 Left to right
~a = 1100 0011
COMMON JAVA OPERATORS /
OPERATOR PRECEDENCE

Precedence Operator Description Associativity


level
10 | Bitwise OR Left to right

Logical Operators
11 && Logical AND
Boolean variables Left to right true and
A holds
variable B holds false then
12 || Logical OR Left to right
(A && B) is false
(A || B) is true
!(A && B) is true
COMMON JAVA OPERATORS /
OPERATOR PRECEDENCE
Assignment Operators
x+=y is same as x=x+y
Precedence Operator Description x-=y is same as x=x-y
Associativity
level x%=y is same as x=x%y
13 = Assignment x|=y is same as x=x|y
Right to left
+= C <<= 2 is same as C = C << 2
Add, assignment
-= Subtract, assignment
*= Multiply, assignment
/= Division, assignment
%= Remainder, assignment
&= Bitwise AND, assignment
^= Bitwise XOR, assignment
|= Bitwise OR, assignment
<<= Left shift, assignment
>>= Right shift, assignment
POST/PRE OPERATORS
 The name of the online example is: Order1.java
public class Order1
{
public static void main (String [] args) Output:
{
int num = 5;
System.out.println(num);
num++;
System.out.println(num);
++num;
System.out.println(num);
System.out.println(++num);
System.out.println(num++);
Fact:
}
} System.out.println inserts a newline (think of println as
print_new_line while if you want everything to stick
together on one line, use System.out.print).
POST/PRE OPERATORS (2)
 The name of the online example is: Order2.java
public class Order2
{
public static void main (String [] args)
{
int num1;
int num2;
num1 = 5; OUTPUT
num2 =num1++ *++num; //5 * 7
System.out.println("num1=" + num1); num1=7
System.out.println("num2=" + num2); num2=35
}
}
UNARY OPERATOR/ ORDER/
ASSOCIATIVY
 The name of the online example:Unary_Order3.java

public class Unary_Order3.java


{
public static void main (String [] args)
{
int num = 5;
System.out.println(num);
num = num * -num; OUTPUT
System.out.println(num);
}
}
USER INPUT USING SCANNER
CLASS
INCLUDING PRE-CREATED JAVA
LIBRARIES
 It’s accomplished by placing an ‘import’ of the appropriate
library at the top of your program.

 Syntax:
import <Full library name>;

 Example:
import java.util.Scanner;
GETTING TEXT INPUT
 You can use the pre-written methods (functions) in the Scanner
class.
 General structure:
import java.util.Scanner;
Creating a scanner
object (something
public static void main (String [] args) that can scan user
input)
{
Scanner <name of scanner> = new Scanner (System.in);
<variable> = <name of scanner> .<method> ();
}
Using the capability of the
scanner object (actually
getting user input)
Getting Text Input (2)
 The name of the online example: MyInput.java
import java.util.Scanner;
public class MyInput
{
public static void main (String [] args)
{
String str1;
int num1;
Scanner in = new Scanner (System.in);
System.out.print ("Type in an integer: ");
num1 = in.nextInt ();
System.out.print ("Type in a line: ");
in.nextLine (); // consumes \n
str1 = in.nextLine ();
System.out.println ("num1:" +num1 +"\t str1:" + str1);
}
}
USEFUL METHODS OF CLASS
SCANNER1
 nextInt ()
 nextLong ()
 nextFloat ()
 nextDouble ()
 nextLine ();
 nextBoolean()
 next();// accept a single word can read only till space
 nextByte();
 nextShort()

1 Online documentation: http://java.sun.com/javase/6/docs/api/


Reading A Single Character
 Text menu driven programs may require this capability.
 Example:
GAME OPTIONS
(a)dd a new player
(l)oad a saved game
(s)ave game
(q)uit game
 There’s different ways of handling this problem but one approach is
to extract the first character from the string.
 Partial example:
String s = "boo“;
System.out.println(s.charAt(0));
Reading A Single Character
 Name of the (more complete example): MyInputChar.java
import java.util.Scanner;

public class MyInputChar


{
public static void main (String [] args)
{
final int FIRST = 0;
String selection;
Scanner in = new Scanner (System.in);
System.out.println("GAME OPTIONS");
System.out.println("(a)dd a new player");
System.out.println("(l)oad a saved game");
System.out.println("(s)ave game");
System.out.println("(q)uit game");
System.out.print("Enter your selection: ");
selection = in.nextLine ();
System.out.println ("Selection: " + selection.charAt(FIRST));
}
}
DECISION MAKING AND LOOP
STRUCTURES
DECISION MAKING IN JAVA
 In programming, decision making is used to specify the
order in which statements are executed.
 if
 if, else
 if, else-if
 switch
DECISION MAKING: LOGICAL OPERATORS

Logical Operation Python Java

AND and &&

OR or ||

NOT not, ! !
DECISION MAKING : If
 An if test is basically the same as the boolean test in a while
loop – except instead of saying,“while it is still raining”
 you’ll say, “ if it is raining”
DECISION MAKING: if
class IfTest { X==3 Yes

public static void main (String[] args) {


Print “x must be 3”
int x = 3;
if (x == 3) {
System.out.println(“x must be 3”);
}
System.out.println(“This runs no matter what”);
} OUTPUT:
} x must be 3
This runs no matter what
Decision Making: If
Format:
if (Boolean Expression) • Indenting the body of the
Body branch is an important
stylistic requirement of
Java but unlike Python it is
Example: not enforced by the
if (x != y) syntax of the language.
System.out.println("X and Y are not equal"); • What distinguishes the
body is either:
if ((x > 0) && (y > 0)) 1. A semi colon (single
{ statement branch)

System.out.println("X and Y are positive"); 2. Braces (a body that


consists of multiple
} statements)
DECISION MAKING: If, Else
Format:
if (Boolean expression)
Body of if No X is Yes
else –ve ?
Body of else
Print: Print :
X is non-negative x is negative
Example:
if (x < 0)
System.out.println("X is negative");
else
System.out.println("X is non-negative");
Example Program: If-Else
 Name of the online example: BranchingExample1.java
import java.util.Scanner;
public class BranchingExample1
{
public static void main (String [] args)
{
Scanner in = new Scanner(System.in);

final int WINNING_NUMBER = 131313;


int playerNumber = -1;
System.out.print("Enter ticket number: ");
playerNumber = in.nextInt();

if (playerNumber == WINNING_NUMBER)
System.out.println("You're a winner!");
else
System.out.println("Try again.");
}
}
DECISION MAKING : If, Else-If
Format: Is False? Then try next
if (Boolean expression) if
Body of if
else if (Boolean expression)
Body of first else-if Is False?
: : :
: : :
else if (Boolean expression)
Is False? Then run the
Body of last else-if
statements in else body
else
Body of else
DECISION MAKING : If, Else-If
DECISION MAKING : If, Else-If (2)
Name of the online example: BranchingExample.java

import java.util.Scanner;

public class BranchingExample2


{
public static void main (String [] args)
{
Scanner in = new Scanner(System.in);
int gpa = -1;
System.out.print("Enter letter grade: ");
gpa = in.nextInt();
If, Else-If (3)
if (gpa == 4)
System.out.println("A");
else if (gpa == 3)
System.out.println("B");
else if (gpa == 2)
System.out.println("C");
else if (gpa == 1)
System.out.println("D");
else if (gpa == 0)
System.out.println("F");
else
System.out.println("Invalid letter grade");
}
}
BRANCHING: WHAT HAPPENS???
if (Boolean Expression)
instruction1;
instruction2;
ALTERNATIVE TO MULTIPLE ELSE-IF’S:
SWITCH
Format (character-based switch):
switch (character variable name)
{ Important! The break is
case '<character value>': mandatory to separate
// Body Boolean expressions
break; (must be used in all but
the last)
case '<character value>':
// Body
break;
:
default:
// Body
}
1 The type of variable in the brackets can be a byte, char, short, int or long
ALTERNATIVE TO MULTIPLE ELSE-IF’S:
SWITCH (2)
Format (integer based switch):
switch (integer variable name)
{
case <integer value>:
Body
break;

case <integer value>:


Body
break;
:
default:
Body
}
1 The type of variable in the brackets can be a byte, char, short, int or long
SWITCH: WHEN TO USE/WHEN NOT
TO USE
 Benefit (when to use):
 It may produce simpler code than using an if-elseif (e.g. , if there are
multiple compound conditions)
 Name of the online example: SwitchExample.java
import java.util.Scanner;
public class SwitchExample
{
public static void main (String [] args)
{
final int FIRST = 0;
String line;
char letter;
int gpa;
Scanner in = new Scanner (System.in);
System.out.print("Enter letter grade: ");
Switch: When To Use/When Not To Use (2)
line = in.nextLine ();
letter = line.charAt(FIRST);
switch (letter)
{
case 'A':
case 'a':
gpa = 4;
break;
case 'B':
case 'b':
gpa = 3;
break;
case 'C':
case 'c':
gpa = 2;
break;
Switch: When To Use/When Not To Use (3)
case 'D':
case 'd':
gpa = 1;
break;

case 'F':
case 'f':
gpa = 0;
break;

default:
gpa = -1;

}
System.out.println("Letter grade: " + letter);
System.out.println("Grade point: " + gpa);
}
}
Switch: When To Use/When Not To Use (4)
 When a switch can’t be used:
 For data types other than characters or integers
 Boolean expressions that aren’t mutually exclusive:
 As shown a switch can replace an ‘if-elseif’ construct
 A switch cannot replace a series of ‘if’ branches).
 Example when not to use a switch:
if (x > 0)
System.out.print(“X coordinate right of the origin”);
If (y > 0)
System.out.print(“Y coordinate above the origin”);
 Example of when not to use a switch:
String name = in.readLine()
switch (name)
{
}
Switch Example: Modified
 What happens if all the ‘break’ instructions have been
removed?
Output:

Enter letter grade: a


Letter grade: a
Grade point: -1
Loops While
Three standard loop structure
Java Pre-test loops
• For
• While
Java Post-test loop For
• Do-while

do while
While Loops
Format:
while (Boolean expression)
Body

Example: true
boolean
int i = 1; statement(s)
expression?
while (i <= 4)
{
// Call function
createNewPlayer();
i = i + 1; false
}
Infinite Loops
 The loop runs infinite times if the value of i
is not decremented at each iteration :
int x = 20;
while(x > 0)
{
System.out.println("x is greater than 0");
x--;
}

4-55
While Loops (boolean test)
public class Loopy {

public static void main (String[] args) {


int x = 1;
System.out.println(“Before the Loop”);
OUTPUT
while (x < 4) {
System.out.println(“In the loop”);
System.out.println(“Value of x is ” + x);
x = x + 1;
}
System.out.println(“This is after the loop”);
}
}
What does the program do?
int x = 4; // assign 4 to x
while (x > 3) {
// loop code will run because
// x is greater than 3
x = x - 1; // or we’d loop forever
}
While Loops
 Code blocks are defined by a pair of curly braces { }
 The assignment operator is one equals sign =
 The equals operator uses two equals signs ==
 A while loop runs everything within its block (defined by curly braces) as
long as the conditional test is true.
 If the conditional test is false, the while loop code block won’t run, and
execution will move down to the code immediately after the loop block.
 Put a boolean test inside parentheses: boolean isHot = true;
while(isHot) { }
 while (x == 4) { }
int x = 1;
while (x){ }
For LOOPS
Format:
for (initialization; Boolean expression; update control)
Body

Example:

for (count =1 ; count <=5 ; count++)


{ Step
Step CreateNewPlayer(); 4
1 }
Step Step
2 3
FOR LOOPS
Initialize

boolean true
statement(s) update
expression?

false
The for Loop Initialization
 The initialization section of a for loop is optional; however, it is
usually provided.
 Typically, for loops initialize a counter variable that will be
tested by the test section of the loop and updated by the
update section.
 The initialization section can initialize multiple variables.
 Variables declared in this section have scope only for the for
loop.

4-61
Multiple Initializations and Updates
 The for loop may initialize and update multiple variables.
for(int i = 5, int j = 0; i < 10 || j < 20; i++, j+=2)
{
statement(s);
}

 Note that the only parts of a for loop that are mandatory
are the semicolons.
for(;;)
{
statement(s);
} // infinite loop
 If left out, the test section defaults to true.
4-62
Do-While: Post-Test Loop
 Recall: Post-test loops evaluate the Boolean expression
after the body of the loop has executed.

 This means that post test loops will execute one or


more times.

 Pre-test loops generally execute zero or more times.


Do-While Loops
Format: statement(s)
do
Body
while (Boolean expression);
true
Example: boolean
char ch = 'A'; expression?
do
{
System.out.println(ch);
ch++;
} false
while (ch <= 'K');
Program output
How high should I go? 7 [Enter]
Creating a user controlled Number for Number
loop
public static void main(String[] args) squared
{ -----------------------------------------
int maxValue; -
1 1
Scanner keyboard = new Scanner(System.in); 2 4
3 9
System.out.print(“How high should I go?4“); 16
maxValue = keyboard.nextInt(); 5 25
6 36
System.out.println(“Number 7
Number squared”); 49
System.out.println(“-----------------------------------------”);

for (int number = 1 ; number <=maxValue ; number++)


4-65
{
Running Totals
 Loops allow the program to keep running totals while
evaluating data.
 Imagine needing to keep a running total of user input.

4-66
import java.text.DecimalFormat;
import javax.swing.JOptionPane;

public class TotalSales


{
public static void main(String[] args)
{
int days;
double sales, totalSales = 0.0;
String input;

DecimalFormat dollar = new DecimalFormat("#,##0.00");

input = JOptionPane.showInputDialog("For how many days do you have sales figures?");


days = Integer.parseInt(input);

for (int count = 1; count <= days; count++)


{
input = JOptionPane.showInputDialog("Enter the sales for day " + count + ": ");
sales = Double.parseDouble(input);
totalSales += sales;
}
JOptionPane.showMessageDialog(null, "The total sales are $“ + dollar.format(totalSales));
System.exit(0);
4-67
}
import java.text.DecimalFormat;
import javax.swing.JOptionPane;

public class TotalSales


{
public static void main(String[] args)
{
int days;
double sales, totalSales = 0.0;
String input;

DecimalFormat dollar = new DecimalFormat("#,##0.00");

input = JOptionPane.showInputDialog("For how many days do you have sales figures?");


days = Integer.parseInt(input);

for (int count = 1; count <= days; count++)


{
input = JOptionPane.showInputDialog("Enter the sales for day " + count + ": ");
sales = Double.parseDouble(input);
totalSales += sales;
}
JOptionPane.showMessageDialog(null, "The total sales are $“ + dollar.format(totalSales));
4-68
System.exit(0);
import java.text.DecimalFormat;
import javax.swing.JOptionPane;

public class TotalSales


{
public static void main(String[] args)
{
int days;
double sales, totalSales = 0.0;
String input;

DecimalFormat dollar = new DecimalFormat("#,##0.00");

input = JOptionPane.showInputDialog("For how many days do you have sales figures?");


days = Integer.parseInt(input);

for (int count = 1; count <= days; count++)


{
input = JOptionPane.showInputDialog("Enter the sales for day " + count + ": ");
sales = Double.parseDouble(input);
totalSales += sales;
}
JOptionPane.showMessageDialog(null, "The total sales are $“ + dollar.format(totalSales));
4-69
System.exit(0);
Logic for Calculating a Running
Total

4-70
Sentinel Values
 Sometimes the end point of input data is not known.
 A sentinel value can be used to notify the program to stop acquiring
input.
 If it is a user input, the user could be prompted to input data that is
not normally in the input data range (i.e. –1 where normal input
would be positive.)
 Programs that get file input typically use the end-of-file marker to
stop acquiring input data.

4-71
public class DoubleNumber
{
public static void main(String[] args)
{
int value, doubleValue;
String input = JOptionPane.showInputDialog("Please enter a value to double (0 to stop):");
value = Integer.parseInt(input);
while (!(value == 0))
{
doubleValue = value*2;

JOptionPane.showMessageDialog(null, value + " doubled is " + doubleValue);

input = JOptionPane.showInputDialog("Please enter a value to double (0 to stop):");


value = Integer.parseInt(input);

}
System.exit(0);
} 4-72
public class DoubleNumber
{
public static void main(String[] args)
{
int value, doubleValue;
String input = JOptionPane.showInputDialog("Please enter a value to double (0 to stop):");
value = Integer.parseInt(input);

while (!(value == 0))


{
doubleValue = value*2;

JOptionPane.showMessageDialog(null, value + " doubled is " + doubleValue);

input = JOptionPane.showInputDialog("Please enter a value to double (0 to stop):");


value = Integer.parseInt(input);
}
System.exit(0);
} 4-73
Nested Loops
 Like if statements, loops can be nested.
 If a loop is nested, the inner loop will execute all of its
iterations for each time the outer loop executes once.
for(int i = 0; i < 10; i++)
for(int j = 0; j < 10; j++)
loop statements;

 The loop statements in this example will execute 100


times.

4-74
import java.text.DecimalFormat;

public class Clock


{ public static void main(String[] args)
{
DecimalFormat fmt = new DecimalFormat("00");
for (int hours = 1; hours <= 12; hours++)
repeats for 12 times
{
for (int minutes = 0; minutes <= 59; minutes++) repeats for 60 times
{
for (int seconds = 0; seconds <= 59; seconds++) repeats for 60 times
{
System.out.print(fmt.format(hours) + ":");
System.out.print(fmt.format(minutes) + ":");
System.out.println(fmt.format(seconds));
}
}
} repeats a total of 12 x 60 x 60 =
} 43,200
}
4-75
The break Statement
 The break statement can be used to abnormally terminate a
loop.
 The use of the break statement in loops bypasses the
normal mechanisms and makes the code hard to read and
maintain.
 If break is used inside nested loop only the inner loop gets
terminated.
 E.g. switch
 It is considered bad form to use the break statement in this
manner.
4-76
The continue Statement
 The continue statement will cause the currently
executing iteration of a loop to terminate and the next
iteration will begin.
 The continue statement will cause the evaluation of
the condition in while and for loops.
 Like the break statement, the continue statement
should be avoided because it makes the code hard to
read and debug. (continue;)

4-77
Deciding Which Loops to Use
 The while loop:
 Pretest loop
 Use it where you do not want the statements to execute if the
condition is false in the beginning.
 The do-while loop:
 Post-test loop
 Use it where you want the statements to execute at least one
time.
 The for loop:
 Pretest loop
 Use it where there is some type of counting variable that can be
evaluated.
4-78
CONTRASTING
PRE VS. POST TEST LOOPS
 Although slightly more work to implement the while loop is the
most powerful type of loop.

 Program capabilities that are implemented with either a ‘for’ or


‘do-while’ loop can be implemented with a while loop.

 Implementing a post test loop requires that the loop control be


primed correctly (set to a value such that the Boolean expression
will evaluate to true the first it’s checked).
EXAMPLE: POST-TEST IMPLEMENTATION
 Name of the online example: PostTestExample.java

public class PostTestExample


{
public static void main (String [] args)
{
final int FIRST = 0;
Scanner in = new Scanner(System.in);
char answer;
String temp;
do
{
System.out.println("JT's note: Pretend that we play our game");
System.out.print("Play again? Enter 'q' to quit: ");
temp = in.nextLine();
answer = temp.charAt(FIRST);
} while ((answer != 'q') && (answer != 'Q'));
}
}
EXAMPLE: PRE-TEST IMPLEMENTATION
 Name of the online example: PreTestExample.java
public class PreTestExample
{
public static void main (String [] args)
{
final int FIRST = 0;
Scanner in = new Scanner(System.in);
char answer = ' ';
String temp;
while ((answer != 'q') && (answer != 'Q'))
{
System.out.println("JT's note: Pretend that we play our game");
System.out.print("Play again? Enter 'q' to quit: ");
temp = in.nextLine();
answer = temp.charAt(FIRST);
}
}
}
MANY PRE-CREATED CLASSES HAVE BEEN
CREATED
 Rule of thumb: Before writing new program code to
implement the features of your program you should check to
see if a class has already been written with the features that
you need.

 The Java API is Sun Microsystems's collection of pre-built Java


classes:
 http://java.sun.com/javase/6/docs/api/
AFTER THIS SECTION YOU
SHOULD NOW KNOW
 The basic structure required in creating a simple Java program as well
as how to compile and run programs
 How to document a Java program
 How to perform text based input and output in Java
 The declaration of constants and variables
 What are the common Java operators and how they work
 The structure and syntax of decision making and looping constructs

You might also like