Class 4: Loops, ifs and cases

The month long hiatus is now over. After much slacking and procrastinating, soJava is back and better than ever. Turns out that I could change the formatting after all and I was just being stupid.

Now that all protocol has been observed, let’s talk about loops, more specifically, while loops, if statements, for loops and case-switch statements.

Very frequently, you will want to make decisions based on given input, do something a certain number of times or do something until something else happens. For that, we will need to make use of either an if, for, while, or case-switch statement. Let’s look at these one by one:

for Loops

A for loop is a definite loop which works it’s way around a given value, or data structure from a start point to an end point unless you break out of it early. For loops in Java follow the given structure.

int total = 0;
int n = 15;
for (int i = 0; i < n + 1; i++){
  total += i;
}
return total

The following code calculates the sum of numbers up to n (15). You initialize a for loop using the for keyword followed by the conditions in parenthesis like (a, b, c) in which a will be the initial position (like int i = 0 N.B The int i is important, don’t forget although you can change the name of i), b is the final position which is up to but not including and c is whether the value is being incremented or decremented (added or subtracted) like i++. 

i++ and i– adds and subtracts 1 to the parameter after the loop goes through at least once respectively.

++i and –1  adds and subtracts 1 to the parameter before the loop goes through at least once respectively.

Once those values have been set, you can include the code which will be run at each value of i inside the curly braces.

while Loops

While loops are definite loops. Given a certain condition, the code in the block will execute until that initial condition is true. for example,

int total = 0;
int n = 15;
while(i <=; 15){
  total += n;
  n--;
}
return total

This is the same code as before, just expressed in a different manner. The code inside the block will keep running until n = 0. While loops are initialized with the while keyword followed by a Boolean expression (something that can be evaluated to true or false) and then the code block. 

There is a variation of while loops called do-while loops which run the code at least once before going through a while loop. I don’t know where you’ll actually need to do this, but just know the option is there if you need it. They basically look like this, 


int total = 0;
int n = 15;
do{
  total += n;
  n--;
}
while(i <=; 15)

return total

It’s basically the same thing, only that it is turned upside down with the code to be executed on top and the condition at the bottom.

if..or…else Statements

Whenever you want to do something different given different pieces of data, you will need to use an if statement to create decisions to run based on input. For example,


if(age > 18 && isVotingYear){
  System.out.println("You can vote this year");
}
else if(age < 21 || isTeatotaller){
  System.out.println("No drink for you!");
}
else{
  System.out.println("What do you want to drink boss?"):
}

Within the parenthesis, you can put a boolean expression or a variable that contains a boolean expression. You can include multiple conditions using || for or &&. Know that Java uses a shortcut evaluation, meaning that as soon as it finds a value that makes a condition true, it terminates making evaluation faster.

while Statements

While/do..while statements are indefinite loops that run while a given condition is true. The difference between while and do..while is that while..do executes the code first before checking if the while loop condition is true. For example, let’s say we want to see how many coins we need to give out as change. (Note that you need to be careful with dealing with money since doubles aren’t perfectly precise.)


System.out.println("Let's see how many coins you get in your change in cents");
int change = sc.nextDouble();
int coins = 0;
while(change != 0){
  if (change - 25 >= 0){
    coins += 1;
    change -= 25;
  }
  else if (change - 10 >= 0){
    coins += 1;
    change -= 10;
  }
  else if (change - 5 >= 0){
    coins += 1;
    change -= 5;
  }
  else (change - 1 >= 0){
    coins += 1;
    change -= 1;
  }
}
System.out.println("You need " + coins + " coins");

Here, the change is being computed by subtracting the largest coin possible given the remaining change to give out.

switch Statements

Switch statements are sort of a neater version of if statements. Basically, you get a statement to evaluate and depending on the case(s), it will execute code based on the statement or a default case if none of the defined cases apply. So, let’s say you want to print hours based on a given day, you would do the following.


Calendar c = new GregorianCalendar;
int day = calendar.get(Calendar.DAY_OF_WEEK);
switch(day){
  // Sunday is 0 through Saturday 6
  case 1:
  case 2:
  case 3:
  case 4:
    System.out.println("Today's hours are 7am to 7pn");
    break;
  case 5:
    System.out.println("Today's hours are 7am to 4:30pm");
    break;
  case 6:
  case 0:
    System.out.println("We are closed today.");
  default:
    System.out.println("Is that a new day?");
    break;
  
}

On each case, you include an expression, like a string or integer and write what you want that particular block to do. To include many, you can put the cases in a chain. Also, after each case, make sure you put a break, or else you will have problems.

So there you have it! An attempt to go through most of the possible conditional statements in Java. This was supposed to come out weeks ago, but then stuff happened so yeah! Here’s the git repo 

Class 4- Loops and Decisions

And due to my lack of confidence, I won’t post an online interpreter with the code. Next time we’ll talk about functions that will help make our code much more readable.

Advertisements