Monday, February 8, 2016

If, Else Statements, and Switch.

If are ways to chose conditionals this can relate directly into real life, for example the problem about milk and eggs, when you go to the store and want to buy milk and eggs you first have to know whether there are milk and eggs. This problem in code would be solved with conditional statements:
int milk = 0;
boolean eggs = true;
if (eggs){
milk = 6;
}
//That indicates what the programmer in the picture thought of //when going to the store
else{
milk = 1;
}
After this you have to make up an alternative to your condition just to make sure that if the condition is false then you are able to get a controlled result this is achieved with an else statement, for the else statement you do not need a condition because one was already stated, however you can use another if statement to add a condition.
int milk = 0;
int eggs = 20;
if (eggs > 0){
milk = 6;
}else if (eggs < 0){
milk = 1;
}
//This will identify that if there is more than 0 eggs there will be 6 bottles of milk, however if there is //no eggs the you'll only buy 1 bottle of milk.
Switch statements help identify different conditionals.
int milk = (int)(Math.random() * 6);//Will randomize the amount of milk from 0-6, remember casting
int eggs;
switch(milk){
case 1: eggs = 1;
          break;
case 2: eggs = 2;
          break;
case 3: eggs = 3;

default : eggs = 4;
          break;
}
This conditional will check the value of milk and will compare it to the different cases that it's given, which will help indicate what block of code to activate, the "break" statement helps finishing the statement, without it the program would do the cases under the one without break until finding a break or a default statement, for example in the case 3 it would assign eggs to the value of 3, but then it would do the default case which assign eggs to 4.

2 comments:

  1. Thanks for that Cesar I look forward to your next weeks post about java!

    ReplyDelete
  2. I really like the way you explain if statements you'd make a great programming teacher

    ReplyDelete