Think in java 答案_Chapter 3_Exercise 3

来源:互联网 发布:用ipad怎么看淘宝直播 编辑:程序博客网 时间:2024/05/01 05:37

阅前声明: http://blog.csdn.net/heimaoxiaozi/archive/2007/01/19/1487884.aspx 

/****************** Exercise 3 ******************
* From the sections labeled "if-else" and
* "return", modify the two test() methods so
* that testval is tested to see if it is within
* the range between (and including) the
* arguments begin and end. (This is a change to
* the exercise in the printed version of the
* book, which was in error).
***********************************************/

public class E03_IfElse3 {
  static boolean
  test(int testval, int begin, int end) {
    boolean result = false;
    if(testval >= begin && testval <= end)
      result = true;
    return result;
  }
  public static void main(String[] args) {
    System.out.println(test(10, 5, 15));
    System.out.println(test(5, 10, 15));
    System.out.println(test(5, 5, 5));
  }
}

//+M java E03_IfElse3

**Since the test( ) methods are now only testing for two conditions, I took the liberty of changing the return value to boolean.

**By using return in the following program, notice that no intermediate result variable is necessary:

// No intermediate 'result' value necessary:
public class E03_IfElse4 {
  static boolean
  test(int testval, int begin, int end) {
    if(testval >= begin && testval <= end)
      return true;
    return false;
  }
  public static void main(String[] args) {
    System.out.println(test(10, 5, 15));
    System.out.println(test(5, 10, 15));
    System.out.println(test(5, 5, 5));
  }
}

//+M java E03_IfElse4

原创粉丝点击