Logical operators and Case statements.
Logical operators in Java
! not
&& and
|| or
^ exclusive or
! is logical negation
&& is logical conjunction
|| logical disjunction
^ logical exclusion
Ruby with the exception of ^ uses the same logical operators, there are also 3 additional options to use which are simply "and" "not" "or."
It's complicated and I don't exactly understand the subtle differences but the symbols have precedence over the actual word versions.
Case statements are used because too many nested if statements can make code very confusing to read. Basically, you can simplify having to make multiple true-false decisions by setting up a case statement for each option.
In Java the syntax works like this
switch (status){
case 0 : do this line of code;
break;
case 1: do this line of code;
break;
case 2: do this line of code;
break;
case 3: do this line of code;
break;
default: System.out.println("you chose an invalid option);
System.exit(0);
}
the program only executes the code according to the case it represents, the break statement tells the program to skip all the other code in the block once it is executed. The default option is there in case a user inputs an option that doesn't match any of the values of the case status. In the above switch statement, the default ouputs that an invalid option has been chosen and terminates the program.
In Ruby you use the term "when" to set up the case like this:
when a=1
do this line of code
when a=2
dot this line of code
else
puts "invalid option selected"
end
In Ruby you use "else" instead of "default"
I also found perusing the googles that you can use multiple values in your when statement.
Here is a link to a very concise and well written explanation about Ruby switch statements.
(Actually quite a bit of good reading on that blog about several different programming subjects)
There we have it for Chapter 3.
Now on to the exercises.
No comments:
Post a Comment