|
Flow ControlAnother major benifit of Java, is the ability to have flow control, that is close to what the machine is actually doing. These are pretty straightforward, so we will blaze right through them. Boolean expressions are important. You can use < > <= >= == or !=. They return 1 for true or 0 for false. (They case implicity to boolean values.) It is important to notice that the == boolean operator is NOT the = assignment operator. Once you have a boolean answer, you can combine them ising && (for and) or || (for or).If statementsIf statements allow you to decide wether or not to execute some lines of code. If the boolean returns true you execute the block or line of code, otherwise you execute the else or keep going if there is none. If there is only one line of code you do not need to surround the block with brackets.if (a > b) { System.out.println( "This worked!"); System.out.print("Isn't it neat?"); } else {System.out.print("No, it is not."); Looping constructsThere are two main looping constructs in Java, for and while. While runs the same section of code over and over, until the condition is no longer true. Example:int x = 0 const int slope = 5; System.out.println ("linear series, slope of " + slope + ", to less than 100:"); while (x < 100) { System.out.println ("x =" + x); x += slope; }The other looping construct is a bit more complex. The for loop has three distinct parts where the condition should go. The first part allows you to initalize a variable to iterate over. The second part is the continuation condition. As long as that condition is true, the code in the block will continue to run. The third part is the iteration command. This is run once each time trough the loop, and tells the for loop how to change the iteration variable. The three parts are separated by semicolons. The following two loops do the same thing: int a = 10; while (a > 0) { System.out.println ("The next number is " + a); a -= 1; } for (int b = 10; b > 0; b--) { System.out.println ("The next number is " + a); } Scope in control structuresLooping structures have their own partial scope. They are not full scope because you can still access variable above them in the function in which they exist, however, you can declare new variables inside the control structure scope, and they do not exist outside of it, for instance:main() { int a = 10; for (int b = 9; b > 6; b--) { int c = 3; a++; } b = 4; // error c = 2; // error }You have to be careful of using the same variable name again in a new variable declaration inside of the partial scope. It hides the old variable, but does not replace it. Thus when you exit the block out to the main function, it will still be there. This is not a good thing to rely on. |