物件導向程式設計

 

 

    3.1 IF流程控制(Flow Control)

 

 


授課教師:陳慶瀚

WWW : http://www.miat.ee.isu.edu.tw/java

E-mail : pierre@isu.edu.tw   

 


3.1 流程控制(Flow Control)

 

3.1.1 if指令

 

All but the most trivial computer programs need to make decisions. They test a condition and operate differently based on the outcome of the test. This is quite common in real life. For instance you stick your hand out the window to test if it's raining. If it is raining then you take an umbrella with you. If it isn't raining then you don't.

All programming languages have some form of an if statement that tests conditions. In the previous code you should have tested whether there actually were command line arguments before you tried to use them.

Arrays have lengths and you can access that length by referencing the variable arrayname.length You test the length of the args array as follows.

 

// This is the Hello program in Java

class Hello {

    public static void main (String args[]) {
    
      if (args.length > 0) {
        System.out.println("Hello " + args[0]);
      }
  }

}
 

System.out.println(args[0]) was wrapped in a conditional test, if (args.length > 0) { }. The code inside the braces, System.out.println(args[0]), now gets executed if and only if the length of the args array is greater than zero.

The arguments to a conditional statement like if must be a boolean value, that is something that evaluates to true or false. Integers are not permissible.

In Java numerical greater than and lesser than tests are done with the > and < operators respectively. You can test whether a number is less than or equal to or greater than or equal to another number with the <= and >= operators.

 

3.1.2 else指令

 

// This is the Hello program in Java

class Hello {

    public static void main (String args[]) {
    
      if (args.length > 0) {
        System.out.println("Hello " + args[0]);
      }
      else {
        System.out.println(
          "Hello whoever you are.");
      }
  }

}
 

3.1.3 else if 指令

if statements are not limited to two cases. You can combine an else and an if to make an else if and test a whole range of mutually exclusive possibilities. For instance, here's a version of the Hello program that handles up to four names on the command line:

 

// This is the Hello program in Java

 class Hello 

{

    public static void main (String args[])

    {

      if (args.length == 0)

        System.out.println("Hello whoever you are");

      else if (args.length == 1)

        System.out.println("Hello " + args[0])

      else if (args.length == 2)

        System.out.println("Hello " + args[0] + " " + args[1]);

      else

        System.out.println("Hello " + args[0] + " " + args[1]

          + " " + args[2]);

   }

}



 

物件導向程式設計

義守大學電機系 陳慶瀚

2001.10.02