Documentation

The Java™ Tutorials
Hide TOC
Questions and Exercises问题和练习
Trail: Learning the Java Language
Lesson: Language Basics

Questions and Exercises: Control Flow Statements问题和练习:控制流语句

Questions问题

  1. The most basic control flow statement supported by the Java programming language is the ___ statement.Java编程语言支持的最基本的控制流语句是if-then语句。
  2. The ___ statement allows for any number of possible execution paths.switch语句允许任意数量的可能执行路径。
  3. The ___ statement is similar to the while statement, but evaluates its expression at the ___ of the loop.do-while语句与while语句类似,但在循环的末尾处计算其表达式。
  4. How do you write an infinite loop using the for statement?如何使用for语句编写无限循环?for(;;){}
  5. How do you write an infinite loop using the while statement?如何使用while语句编写无限循环?

Exercises练习

  1. 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");
    1. What output do you think the code will produce if aNumber is 3?如果aNumber是3,你认为代码会产生什么输出?
    2. Write a test program containing the previous code snippet; make aNumber 3.编写一个包含前面代码段的测试程序;使aNumber为3。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?这是你预测的吗?解释为什么输出是这样的;换句话说,代码段的控制流是什么?
    3. Using only spaces and line breaks, reformat the code snippet to make the control flow easier to understand.仅使用空格和换行符,重新格式化代码段以使控制流更易于理解。
    4. Use braces, { and }, to further clarify the code.使用花括号{}进一步澄清代码。

Check your answers检查你的答案


Previous page: Summary of Control Flow Statements
Next page: Classes and Objects