© 2005 Lawrenceville Press Slide 1 Chapter 6 The while Statement Loop structure that executes a...
-
Upload
hester-dean -
Category
Documents
-
view
218 -
download
0
Transcript of © 2005 Lawrenceville Press Slide 1 Chapter 6 The while Statement Loop structure that executes a...
© 2005 Lawrenceville PressSlide 1
Chapter 6Chapter 6
The while StatementThe while StatementChapter 6Chapter 6
The while StatementThe while Statement Loop structure that executes a set of statements as
long as a condition is true
The condition is a Boolean expression
Will never execute if the condition is initially false
The loop below iterates once because the condition is true and then continues to iterate until response is not 1:
response = 1;while (response == 1) {
System.out.print("Enter 1 or 0:");response = input.nextInt();
}
System.out.println(“response’s value is “+response);
© 2005 Lawrenceville PressSlide 2
Chapter 6Chapter 6
The do-while StatementThe do-while StatementChapter 6Chapter 6
The do-while StatementThe do-while Statement
Alternative form of the while statement
Executes at least once
The do-while statementdo {
System.out.print("Enter 1 or 0:");response = input.nextInt();
} while (response == 1);System.out.print(“response’s value is “+response);
iterates once and continues to iterate until response is not 1.
© 2005 Lawrenceville PressSlide 3
Chapter 6Chapter 6
Infinite LoopsInfinite LoopsChapter 6Chapter 6
Infinite LoopsInfinite Loops A loop that continues executing forever
Can be caused by syntax or logic errors. For example:
while (num < 0) //error--no bracesSystem.out.print("Enter a vale: ");num = input.nextInt();
Accidental creation of an empty loop body by putting a Accidental creation of an empty loop body by putting a semicolon in the wrong place or if a counter is not semicolon in the wrong place or if a counter is not incremented or decremented.incremented or decremented.
Some errors can result in an overflow
if you were adding to a integer variable eventually the maximum value would be reach then an overflow would occur.
© 2005 Lawrenceville PressSlide 4
Chapter 6Chapter 6
CountersCountersChapter 6Chapter 6
CountersCounters A variable that is incremented by a constant
value
Often used for counting loop iterations
Should be initialized to 0 when declared
The counter in the loop counts the number of responses:
do {System.out.print("Enter 1 or 0:");response = input.nextInt();numResponses += 1;
} while (response == 1);System.out.println(“Finished”);
© 2005 Lawrenceville PressSlide 5
Chapter 6Chapter 6
AccumulatorsAccumulatorsChapter 6Chapter 6
AccumulatorsAccumulators
A variable that is incremented by a varying amount
Often used for summing
Should be initialized to 0 when declared
The accumulator in the loop sums values:do {
System.out.print("Enter grade:");grade = input.nextInt();sumOfGrades += grade;
} while (grade != 999);System.out.println(“Done”);
© 2005 Lawrenceville PressSlide 6
Chapter 6Chapter 6
Using FlagsUsing FlagsChapter 6Chapter 6
Using FlagsUsing Flags
A flag, or sentinel, indicates when a loop should stop iterating
Often a constant
Code is easier to modify when sentinels are constants declared at the beginning of an application
A flag is used in the condition of the loop:final int STOP = 999;do {
System.out.print("Enter grade:");grade = input.nextInt();sumOfGrades += grade;
} while (grade != STOP);
© 2005 Lawrenceville PressSlide 7
Chapter 6Chapter 6
The for StatementThe for StatementChapter 6Chapter 6
The for StatementThe for Statement
Loop structure that executes a set of statements a fixed number of times
Uses a loop control variable (lcv)
The increment (++) or decrement (--) operators are used to change the value of the loop control variable
The loop below executes until i is greater than 10:
for (int i = 0; i <= 10; i++) {sum += i;
}
What is the value of sum when loop terminates?
© 2005 Lawrenceville PressSlide 8
Chapter 6Chapter 6
Debugging TechniquesDebugging TechniquesChapter 6Chapter 6
Debugging TechniquesDebugging Techniques
The debugger included with many compilers
Variable trace, which is a manual technique of list values of variables at the points of assignment
Additional println() statements for displaying variable values at points of assignment
"Commenting out" code to detect bugs through a process of elimination
© 2005 Lawrenceville PressSlide 9
Chapter 6Chapter 6
Variable TraceVariable TraceChapter 6Chapter 6
Variable TraceVariable Trace
int num1 = 0;int num2 = 0;while (num1 < 10) {
if (num1 % 3 == 0) {num2 += num1;System.out.print(num2 + "
");}num1 += 1;
}
© 2005 Lawrenceville PressSlide 10
Chapter 6Chapter 6
Using println() to DebugUsing println() to DebugChapter 6Chapter 6
Using println() to DebugUsing println() to Debug
int num1 = 0;int num2 = 0;System.out.println("num1 before while: " + num1);//debugwhile (num1 < 10) {
System.out.println("num1 in while: " + num1);//debug
if (num1 % 3 == 0) {num2 += num1;System.out.println("num2: " + num2);
//debugSystem.out.print(num2 + " ");
}num1 += 1;
}
© 2005 Lawrenceville PressSlide 11
Chapter 6Chapter 6
Using Comments to DebugUsing Comments to DebugChapter 6Chapter 6
Using Comments to DebugUsing Comments to Debug
int num1 = 0;int num2 = 0;while (num1 < 10) {
//if (num1 % 3 == 0) {// num2 += num1;// System.out.print(num2 + "
");//}num1 += 1;
}
© 2005 Lawrenceville PressSlide 12
Chapter 6Chapter 6
The String ClassThe String ClassChapter 6Chapter 6
The String ClassThe String Class
Part of the java.lang package
A String object is comprised of a sequence of characters with the first character at index position 0
String methods include:length()substring()toLowerCase()toUpperCase()trim()replaceFirst()replaceAll()
© 2005 Lawrenceville PressSlide 13
Chapter 6Chapter 6
String Data and the Scanner String Data and the Scanner ClassClass
Chapter 6Chapter 6
String Data and the Scanner String Data and the Scanner ClassClass
The next() method should be used for reading string data after numeric data has been read. If the nextLine() method is used, the end-of-line character left by the numeric entry is read and any text typed is ignored.
System.out.print("Enter age: ");age = input.nextInt();System.out.print("Enter first name: ");firstName = input.next();
© 2005 Lawrenceville PressSlide 14
Chapter 6Chapter 6
String Data and the Scanner Class String Data and the Scanner Class (con't)(con't)
Chapter 6Chapter 6
String Data and the Scanner Class String Data and the Scanner Class (con't)(con't)
Alternatively, a statement can be added to read the end-of-line character left by the numeric entry, so that the nextLine() method can be used to read a string that may contain white space:
System.out.print("Enter age: ");age = input.nextInt();input.nextLine(); //remove end-of-lineSystem.out.print("Enter full name: ");fullName = input.nextLine();
© 2005 Lawrenceville PressSlide 15
Chapter 6Chapter 6
String AssignmentString AssignmentChapter 6Chapter 6
String AssignmentString Assignment
Strings are immutable. Assigning a new string to a String object simply changes the object reference to point to the new string in memory:
String text;text = "heLlO";text = text.toLowerCase();
texttextheLlO
hello
© 2005 Lawrenceville PressSlide 16
Chapter 6Chapter 6
Comparing StringsComparing StringsChapter 6Chapter 6
Comparing StringsComparing Strings
The String class includes several methods for comparing two strings:
equals()equalsIgnoreCase()compareTo()compareToIgnoreCase()indexOf()lastIndexOf()startsWith()endsWith()