Java Toturial 3 - Control Flow

来源:互联网 发布:校园app 软件下载 编辑:程序博客网 时间:2024/05/18 01:26
 
  1. Conditional Statements(IF)

  • Conditional statements execute a block or set of other statements only if certain conditions are met.
    if (name == "Fred")
    {x = 4;}
    else
    {x = 20;};
    Whenthe conditional if statement is used only to make an assignment to onevariable, you can use the terse C conditional operator.
    x = (name == "Fred") ? 4 : 20;
  1. Loops (FOR,WHILE)
  • For statements allow a set of statements to be repeated or looped through a fixed number of times.
  • The round bracket contains initializer(s) ; conditional test ;incrementer(s). If more than one initializer or incrementer is usedthey are separated with commas. The test condition is checked prior toexecuting the block. The incrementing is completed after executing theblock.
  • for (int i=1; i<=15; i++) { document.writeln("#"+i); };
  • While statements allow a set of statements to be repeated or looped until a certain condition is met.
  • The test condition is checked prior to executing the block
  • int i = 0;while (i<=5) { document.writeln("#"+i); i = i + 1; };
  • DoWhile statements allow a set of statements to be repeated or loopeduntil a certain condition is met. The test condition is checked afterexecuting the block.
  • int i = 1;do { document.writeln("#"+i); i = i + 1; } while (i<=5);
  1. The Switch Statement(switch case)
  • Switch(or case) statements are used to select which statements are to beexecuted depending on a variable's value matching a label. default isused for the else situation.

switch (selection)
{
case '1': System.out.println("You typed a 1"); break;
case '2': System.out.println("You typed a 2"); break;
case '3': System.out.println("You typed a 3"); break;
case '4': System.out.println("You typed a 4"); break;
default : System.out.println("Oops!, that was an invalid entry.");
};

  1. Continue, Break and Return
  • Continuestatements are used in looping statements to force another iteration ofthe loop before reaching the end of the current one.
  • Break statements are used in looping and 'switch' statements to force an abrupt termination or exit from the loop or switch.
  • Return statements are used to force a quick exit from a method. They are also used to pass values back from methods.
  1. Command Line Arguments
  • Command line arguments are accessible through the args array.
  • The array does not include the interpreter java command or the class name and the count starts at 0.
  • Each argument is passed as a string but may be converted to other types

 

 

i wanna run away never say goodbey