目录

  • 1 Java语言概述
    • 1.1 Java语言的特点
    • 1.2 Java虚拟机
    • 1.3 Java开发环境
    • 1.4 编译执行和解释执行
    • 1.5 第一个java程序1
    • 1.6 第一个java程序2
    • 1.7 第一个java程序3
    • 1.8 章节测验
  • 2 Java基础语法
    • 2.1 基本数据类型
    • 2.2 赋值语句
    • 2.3 表达式
    • 2.4 运算符
    • 2.5 类型转换
    • 2.6 章节测验
  • 3 类与对象
    • 3.1 面向对象的概念
    • 3.2 类和对象的概念
    • 3.3 构造方法
    • 3.4 章节测验
  • 4 继承与多态
    • 4.1 继承
    • 4.2 多态
    • 4.3 final关键字
    • 4.4 static关键字
    • 4.5 抽象类
    • 4.6 接口
    • 4.7 内部类
    • 4.8 章节测验
  • 5 数组和字符串
    • 5.1 数组
    • 5.2 字符串
    • 5.3 章节测验
  • 6 常用类与接口
    • 6.1 课件
    • 6.2 重要知识点
  • 7 异常处理
    • 7.1 课件
    • 7.2 重要知识点
  • 8 文件和流
    • 8.1 课件
    • 8.2 重要知识点
  • 9 Elements of Programming
    • 9.1 You First Program
      • 9.1.1 Exercise
      • 9.1.2 Program
    • 9.2 Built-in Types of Data
      • 9.2.1 Exercise
      • 9.2.2 Program
    • 9.3 Conditionals and Loops
      • 9.3.1 Exercise
      • 9.3.2 Program
    • 9.4 Arrays
      • 9.4.1 Exercise
      • 9.4.2 Program
    • 9.5 Input and Output
      • 9.5.1 Exercise
      • 9.5.2 Program
    • 9.6 Case Study: Random Web Surfer
  • 10 Functions
    • 10.1 Static Methods
      • 10.1.1 Exercise
      • 10.1.2 Program
    • 10.2 Libraries and Clients
      • 10.2.1 Exercise
      • 10.2.2 Program
    • 10.3 Recursion
      • 10.3.1 Exercise
      • 10.3.2 Program
    • 10.4 Case Study: Percolation
  • 11 Object-Oriented Programming
    • 11.1 Using Data Types
    • 11.2 Creating Data Types
    • 11.3 Designing Data Types
    • 11.4 Case Study: N-Body Simulation
  • 12 参考资料
    • 12.1 主要参考书
    • 12.2 慕课资源
Conditionals and Loops

In the programs that we have examined to this point, each of the statements is executed once, in the order given. Most programs are more complicated because the sequence of statements and the number of times each is executed can vary. We use the term control flow to refer to statement sequencing in a program. (流程控制语句:整体的语法规则和C语言一致)


If statements.

 Most computations require different actions for different inputs.

  • The following code fragment uses an if statement to put the smaller of two int values in x and the larger of the two values in y, by exchanging the values in the two variables if necessary.

  • Flip.java uses Math.random() and an if-else statement to print the results of a coin flip.


  • The table below summarizes some typical situations where you might need to use an if or if-else statement.

While loops.

 Many computations are inherently(天生的) repetitive. The while loop enables us to execute a group of statements many times. This enables us to express lengthy computations without writing lots of code.

  • The following code fragment computes the largest power of 2 that is less than or equal to a given positive integer n.


  • TenHellos.java prints "Hello World" 10 times.

  • PowersOfTwo.java takes an integer command-line argument n and prints all of the powers of 2 less than or equal to n.


For loops.

 The for loop is an alternate Java construct that allows us even more flexibility when writing loops.

  • For notation. Many loops follow the same basic scheme: initialize an index variable to some value and then use a while loop to test an exit condition involving the index variable, using the last statement in the while loop to modify the index variable. Java's for loop is a direct way to express such loops.

  • Compound assignment idioms. The idiom(风格、语法) i++ is a shorthand(简略表示) notation(标记、符号) for i = i + 1.

  • Scope. The scope of a variable is the part of the program that can refer to that variable by name. Generally the scope of a variable comprises(包含) the statements that follow the declaration in the same block as the declaration. For this purpose, the code in the for loop header is considered to be in the same block as the for loop body.


Nesting. (嵌套)

The ifwhile, and for statements have the same status as assignment statements or any other statements in Java; that is, we can use them wherever a statement is called for. In particular, we can use one or more of them in the body of another statement to make compound statements. To emphasize the nesting, we use indentation(缩进) in the program code.

  • DivisorPattern.java has a for loop whose body contains a for loop (whose body is an if-else statement) and a print statement. It prints a pattern of asterisks(星号) where the i th row has an asterisk in each position corresponding to divisors(除数) of i (the same holds true for the columns). (要求看懂代码,并能分析运行结果)

  • MarginalTaxRate.java computes the marginal tax rate(边际税率) for a given income. It uses several nested if-else statements to test from among a number of mutually(互相的) exclusive possibilities.


  • Loop examples.


    Applications.

    The ability to program with loops and conditionals immediately opens up the world of computation to us.(循环+条件:打开计算世界的大门)

  • Ruler subdivisions. RulerN.java takes an integer command-line argument n and prints the string of ruler subdivision(尺度细分) lengths. This program illustrates one of the essential characteristics of loops—the program could hardly be simpler, but it can produce a huge amount of output.(极简单的代码,产生大量的输出)

  • Finite sums. The computational paradigm used in PowersOfTwo.java is one that you will use frequently. It uses two variables—one as an index that controls a loop, and the other to accumulate a computational result. Program HarmonicNumber.java uses the same paradigm(范例) to evaluate the sum


    These numbers, which are known as the harmonic numbers(调和数), arise frequently in the analysis of algorithms.

  • Newton's method.  Sqrt.java uses a classic iterative technique known as Newton's method to compute the square root of a positive number x: Start with an estimate t. If t is equal to x/t (up to machine precision), then t is equal to a square root of x, so the computation is complete. If not, refine the estimate by replacing t with the average of t and x/t. Each time we perform this update, we get closer to the desired answer.

  • Number conversion. Binary.java prints the binary (base 2) representation of the decimal number typed as the command-line argument. It is based on decomposing the number into a sum of powers of 2. For example, the binary representation of 106 is 11010102, which is the same as saying that 106 = 64 + 32 + 8 + 2. To compute the binary representation of n, we consider the powers of 2 less than or equal to n in decreasing order to determine which belong in the binary decomposition (and therefore correspond to a 1 bit in the binary representation).

  • Gambler's ruin(赌徒的破产). Suppose a gambler makes a series of fair $1 bets, starting with $50, and continue to play until she either goes broke or has $250. What are the chances that she will go home with $250, and how many bets might she expect to make before winning or losing?  Gambler.java is a simulation that can help answer these questions. It takes three command-line arguments, the initial stake ($50), the goal amount ($250), and the number of times we want to simulate the game.


  • Prime factorization(质因子分解). Factors.java takes an integer command-line argument n and prints its prime factorization. In contrast to many of the other programs that we have seen (which we could do in a few minutes with a calculator or pencil and paper), this computation would not be feasible(可行的) without a computer.


  • Other conditional and loop constructs.

    To be complete, we consider four more Java constructs related to conditionals and loops. They are used much less frequently than the ifwhile, and for statements that we've been working with, but it is worthwhile to be aware of them.(虽然用的少,但是不可忽略)

    • Break statements. In some situations, we want to immediate exit a loop without letting it run to completion. Java provides the break statement for this purpose. Prime.java takes an integer command-line argument n and prints true if n is prime(质数、素数), and false otherwise. There are two different ways to leave this loop: either the break statement is executed(执行) (because n is not prime) or the loop-continuation condition is not satisfied (because n is prime).

      Note that the break statement does not apply to if or if-else statements. (注意:break不能乱用,看下面的案例). In a famous programming bug, the U.S. telephone network crashed because a programmer intended to use a break statement to exit a complicated if statement.

    • Continue statements. Java also provides a way to skip to the next iteration of a loop: the continue statement. When a continue is executed within the body of a for loopy, the flow of control transfers directly to the increment statement for the next iteration of the loop.

    • Switch statements. The if and if-else statements allow one or two alternatives. Sometimes, a computation naturally(天生的自然的) suggests more than two mutually(互相的) exclusive alternatives. Java provides the switch statement for this purpose. NameOfDay.java takes an integer between 0 and 6 as a command-line argument and uses a switch statement to print the corresponding name of the day (Sunday to Saturday).

    • Do–while loops. A do-while loop is almost the same as a while loop except that the loop-continuation condition is omitted the first time through the loop. RandomPointInCircle.java sets x and y so that (xy) is randomly distributed inside the circle centered at (0, 0) with radius 1.

    With Math.random() we get points that are randomly distributed in the 2-by-2 square center at (0, 0). We just generate points in this region until we find one that lies inside the unit disk. We always want to generate at least one point so a do-while loop is most appropriate. We must declare x and y outside the loop since we will want to access their values after the loop terminates.

    We don't use the following two flow control statements in this textbook, but include them here for completeness. (为了完整性仅作介绍,不推荐使用)

    • Conditional operator. The conditional operator ?: is a ternary operator (three operands) that enables you to embed a conditional within an expression. The three operands are separated by the ? and : symbols. If the first operand (a boolean expression) is true, the result has the value of the second expression; otherwise it has the value of the third expression.

      int min = (x < y) ? x : y;

    • Labeled break and continue statements. The break and continue statements apply to the innermost(最深处) for or while loop. Sometimes we want to jump out of several levels of nested loops. Java provides the labeled break and labeled continue statements to accomplish this. Here is an example.