|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
- Question: Look at the
SortDemoprogram. What control flow statements does it contain?
Answer:SortDemocontains four control statements. In order: twoforstatements, anifstatement, and anotherforstatement.- Question: What's wrong with the following code snippet:
if (i = 1) { /* do something */ }
Answer: It should use==instead of=. If you try to compile the preceding code, the compiler warns you that abooleanvalue is required instead of anintvalue.- Question: Look at the
WhileDemoprogram and the
DoWhileDemoprogram. What would the output be from each program if you changed the value of each program's
copyFromMestring togolly gee. this is fun.Explain why you think each program will have the predicted output.
Answer:NewWhileDemoand
NewDoWhileDemo. The modified
WhileDemodisplays a blank line because the first letter is ag, and thus the loop is not entered and no characters are appended tocopyToMe. The modifiedDoWhileDemodisplaysgollybecause the firstgis ignored, and the second one terminates the loop without adding the secondgto the string.
- Consider the following code snippet.
if (aNumber >= 0) if (aNumber == 0) System.out.println("first string"); else System.out.println("second string"); System.out.println("third string");
- Exercise: What output do you think the code will produce if
aNumberis 3?
Solution:second string third string- Exercise: Write a test program containing the code snippet; make
aNumber3. What is the output of the program? Is it what you predicted? Explain why the output is what it is. In other words, what is the control flow for the code snippet?
Solution:NestedIf3 is greater than or equal to 0, so execution progresses to the secondsecond string third stringifstatement. The secondifstatement's test fails because 3 is not equal to 0. Thus, theelseclause executes (since it's attached to the secondifstatement). Thus,second stringis displayed. The finalprintlnis completely outside of anyifstatement, so it always gets executed, and thusthird stringis always displayed.- Exercise: Using only spaces and line breaks, reformat the code snippet to make the control flow easier to understand.
Solution:if (aNumber >= 0) if (aNumber == 0) System.out.println("first string"); else System.out.println("second string"); System.out.println("third string");- Exercise: Use braces
{and}to further clarify the code and reduce the possibility of errors by future maintainers of the code.
Solution: Adhering to the Sun code conventions:if (aNumber >= 0) { if (aNumber == 0) { System.out.println("first string"); } else { System.out.println("second string"); } } System.out.println("third string");
|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2004 Sun Microsystems, Inc. All rights reserved.