Picture
I think after 3 more days, we can begin actual game development.

Of course there's a lot more to learn, but I think it would be more fun and more efficient to learn some of the tougher concepts by application.

Without further ado, let's jump into our next lesson!

Lesson #1-16: Analyzing the Looping Class

In the last lesson, I created a class called Looping as follows: 
Picture
Picture
The Output:
Picture
It might have been a while since we discussed some of these concepts, so please refer to previous lessons if you are confused!
And of course, you can comment below with questions as always.

Now to analyze:

1. The blue text begins the Looping class. (I hope you know this by now  ).
2. The light blue text then begins the main method (you should know what the main method is also).

3. The next three statements beginning "int..." initialize three integers: initialValue, finalValue, and counter.

4. The point of this program is to count from a lower number to a higher number, so the first condition it tests for, using an if statement is whether initialValue < finalValue.

5. If this condition is satisfied, we see a bunch of System.out.println("...")

6. The counter variable is increased by 1.

7. The while loop then initiates, and this increases initialValue by 1, and displays the new initialValue.

8. Counter variable is again increased by 1.

9. With each iteration (repetition) of the while loop, we check if the initialValue (which increases by 1 with each iteration) is equal to finalValue, because that is when we can stop counting.

10. When this if condition (colored gold) is satisfied, we stop counting, and display the counter variable, which has been increasing by 1 with each increase in value of the initialValue variable.


Make sure you run this code a few times with your own numbers to understand what exactly is happening at each step.

If you want to make your own programs, you should be able to analyze and at least have a general sense of what other programmers are trying to accomplish with their code.

Lesson #1-17: The For Loop

The while loop utilized a counter that we coded ourselves. Now we will implement the for loop which comes with a built-in counter, so to speak. 

The form of a for loop is as follows (as stated in Java docs): 
Picture
"When using this version of the for statement, keep in mind that:

1. The initialization expression initializes the loop; it's executed once, as the loop begins.
2. When the termination expression evaluates to false, the loop terminates.
3. The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value."

Confused?

Let's look at an example: 
Picture
The output would be: 
Picture
The for loop is quite simple:

The first part of the for (...) is the initialization of a variable.
We initiate an integer called variable, with the value of 1.

The second part "variable <11" is the condition. Think of this as: while (variable < 11)...
Everything inside the for loop will run as long as this second part is satisfied.

The third part "variable++" is what happens to the initialized variable after each iteration. We increase it by one.


Lesson #1-18: Applying the For Loop

In this lesson, we will recreate the Looping program using not the while loop, but the for loop!

Have a look at the while loop example again: 
Picture
Picture
We can safely remove all the counter variable related statements, as the for loop will handle that for us.
The only other segment of code we need to modify is the while loop section.

We will replace this with the for loop : 
public class ForLooping {
    public static void main(String[] args) {

        int initialValue = 0;
        int finalValue = 10;
        int counter = 0;

        if (initialValue < finalValue) {
            System.out.println("Input accepted!");
            System.out.println("Initial Value: " + initialValue);
            System.out.println("Final Value: " + finalValue);
            System.out.println();
            System.out.println("Initiating count.");
            System.out.println();

            System.out.println(initialValue);
            counter++;
           
            for (initialValue = 1; initialValue < finalValue + 1; initialValue++) {
                System.out.println(initialValue);
                counter++;
               
                if (initialValue == finalValue){
                     System.out.println();
                     System.out.println("Counting complete.");
                     System.out.println("There are " + counter + " numbers (inclusive) between " + (initialValue - counter + 1) + " and " + finalValue + ".");
                }
            }
                   
        } else {
            System.out.println("Final value is less than initial value!");
            System.out.println("Please choose new values.");
        }

    }
}
Remember to change the name of the class (Select it on the left side of the screen in the Package Explorer, use F2) before running the code!

Also, this code is not color coded. Try to keep track of what each pair of braces contain. An easy way to do this is to start from the highest level and go deeper into the code: (Class, main method, if statement, for loop, if statement). The indentations should help you discern which braces correspond. 

If you need help, refer to the previous class "Looping." It is mostly similar.
Also if you copy and paste this into Eclipse, you can click next to a curly brace and Eclipse will draw a small rectangle on its counterpart to make it easier to tell.

Ctrl + Shift + F automatically indents your code for you! Use that well.


The output: 
Picture
Using the for loop is another way to do the same work! 

This concludes Day 9.
Picture
 


Comments

Reece
11/16/2012 9:20pm

Thanks!

Reply
Zak
12/06/2012 9:16pm

In your first example explaining the For Loop there is a minor error. you were missing a parentheses. it should look like this.

for(int variable = 1; variable <11; variable++) {
System.out.println("Count is: " + variable);
}

and in the applying the for loop. I see what's missing but don't get exactly how it's working. Like what part actually says initialValue == finalValue. or is that missing? because when you run the code you no longer get the there 11 numbers between 0 and 10. so maybe that's throwing me off.

Could you just add that in? (I'm actually gonna just try this real quick.. but I'd still appreciate any input that may help clarify this for me.) Thanks!

Reply
James C.
12/07/2012 10:12am

Thank you so much for catching my mistakes.

Everything was fixed!

Reply
Dnnis
01/03/2013 7:52pm

Hello Can you explain to me this part of the Syntaxis please?

for (initialValue = 1; initialValue < finalValue + 1; initialValue++)

I understand the For loop but I got Confused when you write this "finalValue + 1" ......what did you do it?

Reply
dnnis
01/03/2013 7:53pm

Reply
Sparsh
01/07/2013 9:16am

Yeah....
I am too stuck in the same statement as Dnnis.
Also why cant we use initialValue<=finalValue instead of using initialValue<finalValue+1???

Reply
James C
01/07/2013 9:24am

It's always a good idea to have a < not a <= inside a for loop. It behaves in more predictable ways (because of the way it increments).

To keep it a <. I added a + 1.

Reply
James C.
01/07/2013 9:37am

Although now that I look at it, i probably should have initialized it at 0. :)

Refer to the answer in this link:
http://stackoverflow.com/questions/182600/should-one-use-or-in-a-for-loop

The key word is "idiomatic."

Adrian
02/02/2013 10:07pm

Hi love the tutorial so far. looking forward to getting further in.

Just a comment on the code :
for (initialValue = 1; initialValue < finalValue + 1; initialValue++) {
System.out.println(initialValue);
The only thing I see here is for the class to work correctly initialValue needs to be 0. If you change initialValue to be anything else the output becomes incorrect.
I know eclipse produces a warning but the line could be changed to

for (initialValue = initialValue; initialValue < finalValue + 1; initialValue++) {

to fix this. either that or the loop could use another assignment variable to track its' looping other than initialValue

Reply
Chuck
02/09/2013 6:01pm

I seen this too, so I came up with this simple little fix.
for (initialValue = initialValue + 1; ...

Reply
Chuck
02/09/2013 5:46pm

I decided to remove all the counters and initiate a "difference" that = finalValue - initialValue, then reference it later where counters were used. What kinds of pros/cons could there be to this?
It worked and everything, but to get difference + 1 to work for the number count statement, I had to type it like this:

System.out.println("There are " + (difference + 1)
+ " numbers (inclusive) between "
+ (initialValue - difference) + " and "
+ finalValue + ".");
I'm surprised it worked. :P

Reply
Andreas
04/12/2013 2:56pm

The example greatly benefits if you start the for loop like

for ( initialValue = 0; initialValue <= finalValue; initialValue++ )

Though you are right to point out that "greater or equal" comparison has a risk one just has to avoid comparing against the maximum value for the _type_ of the loop counter to overcome this problem.

Reply
Yousef
08/24/2013 7:51am

I was trying to test myself by seeing the output before reading your source code, then I wrote my code in Eclipse. After writing my code I found out that there is a little difference between my code and yours, and I just want you to tell me if it's bad practice or not.

public class Test {
public static void main(String[] args) {
int initialValue = 0;
int finalValue = 10;
int counter = 0;

if (initialValue < finalValue) {
System.out.println("Input accepted!");
System.out.println("Initital value: " + initialValue);
System.out.println("Final value: " + finalValue);
System.out.println();
while (initialValue <= finalValue) {
System.out.println(initialValue);
initialValue++;
counter++;
}
System.out.println();
System.out.println("Counting complete.");
System.out.println("There are " + counter + " numbers between "
+ (initialValue - counter) + " and " + finalValue + ".");
} else {
System.out.println("Invaild.");
}

}
}

Reply
ahmed
09/05/2013 6:50pm

System.out.println(intialvalue);
didn't print 0 value and printed it as intialvalue
what that mean?
and thanx

Reply



Leave a Reply

    Author

    James Cho is the lead developer at Kilobolt Studios. He is a college student at Duke University and loves soccer, music, and sharing knowledge.