Java Tutorial #12 — Loops in action, and number casting

Taking a step back to sanity on this one, sorry about the difficulty of lesson 11


Topics Discussed: Using a loop to count something for us.

Source Code Available Here

HomeWork is Available Here


Casting numbers
Casting numbers is an important part of any programming language that has certain roles that numbers fall into. The basic idea is this: assume that you have two numbers that you would like to divide, let’s assume you have 12 items that you want to divide equally among 7 people, assuming that we were to type that problem into java as an integer, we would get the following:
12 / 7 = 1
We can clearly see that this is wrong, but when you think about it, it’s also right. An integer cannot possibly hold a decimal value, therefore it being > 1.5 does not mean it will be rounded or anything of the sort… everything after the decimal place is truncated and discarded. Thus 1.71 (12/7) becomes 1. The way to have this resolve as we would like is as follows:


12/7.0; // 1.71.....

Now there’s a lot of different ways that you can cast numbers like this, here is a non-complete list of ways that you can cast integers into doubles for a moment:


 double a=0, b=0, c=0, d=0, e=0, f=0, g=0;
       
       a = 12/7;
       b = 12.0/7;
       c = 12/7.0;
       d = 12.0/7.0;
       e = (double)(12)/7;
       f = 12/(double)(7);
       g = (double)(12)/(double)(7);

       System.out.println("a = "+ a);
       System.out.println("b = "+ b);
       System.out.println("c = "+ c);
       System.out.println("d = "+ d);
       System.out.println("e = "+ e);
       System.out.println("f = "+ f);
       System.out.println("g = "+ g);

The output of the above is as follows:

Program output:
a = 1.0
b = 1.7142857142857142
c = 1.7142857142857142
d = 1.7142857142857142
e = 1.7142857142857142
f = 1.7142857142857142
g = 1.7142857142857142


Using a loop to increment a number
Essentially, we’re taking a number defined outside the scope of the loop and incrementing it by the counter of the loop:


int total=0;

for (int i=0; i<10; i++){
     total += i;
}

In the above example we are incrementing total by using the contents of i each time through the loop. If we preserve i for use outside the loop we can easily find the average by dividing out total by the final value of i.