|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
- Two questions about
WhileDemoand
DoWhileDemo.
Question: What would the output be from
WhileDemoand
DoWhileDemoif you change the value of the string
copyFromMeto"golly gee. this is fun"?
Answer:WhileDemodisplays nothing.DoWhileDemodisplaysgolly.Question: Would the output be different? Defend your answer.
Answer: The output is different. The expressionc != 'g'is evaluated at the top of the loop inWhileDemo. Because the first character of the string is a 'g' the statements within the loop are never executed. InDoWhileDemothe expression is evaluated at the bottom of the loop after the first 'g' is appended to the string buffer. Thus the expression tests the second character in the string, which is an 'o'. The loop continues until the second 'g' in the string.
- Question: Identify the control flow statements in the
SortDemoprogram.
Answer:public class SortDemo { public static void main(String[] args) { int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076, 2000, 8, 622, 127 }; for (int i = arrayOfInts.length; --i >= 0; ) { for (int j = 0; j < i; j++) { if (arrayOfInts[j] > arrayOfInts[j+1]) { int temp = arrayOfInts[j]; arrayOfInts[j] = arrayOfInts[j+1]; arrayOfInts[j+1] = temp; } } } for (int i = 0; i < arrayOfInts.length; i++) { System.out.print(arrayOfInts[i] + " "); } System.out.println(); } }
|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |