PDA

View Full Version : Using the for/for each loop


The Soul
08-27-2009, 07:11 AM
Description - Using and learning the for/for each loop

Difficulty - 2/10, it's more of a learning tutorial

Tested Server - No server

The purpose of the tutorial is to learn about the for loop, and several examples of its purpose.


Simple for statement:
for(byte b = 0; b < 10; b++) {
System.out.println("Number: " + b) ;
}

If you were to run this, it would print out 'Number: 0-9' in the command prompt.

byte b = 0; // this is the declaration of this integer. We're using 'b' as the iterator because it's short and simple. You can use anything you want.

b < 10; // this means that if 'b' were to be greater than 10, the loop will conclude.

b++ // this means that 'b' will increment.


An example of the for loop in private servers would be for what you all probably know as the 'master' command.

Instead of having 25 or so lines for a command, you can shorten it to about 4.

if (command.equalsIgnoreCase("master") {
for (byte b = 0; b < 24; b++) {
addSkillXP(Integer.MAX_VALUE, b) ; // using the MAX_VALUE constant of the Integer class, and using 'b' as the amount of skills you want to increase.
}
}



________________________



These for loops can also be used to loop through arrays.

For example, you can make it so it loops through an array of Strings to check if the user is typing something within that array, and if so, it won't send the message.

if(command.equals("yell")) {
String[] array = {"abc", "dfg", "hij"};
for(byte b = 0; b < array.length; b++) {
if(command.contains(b) return;
yell(playerName + command.substring(5));
}

Or you could use the for each loop.

if(command.equals("yell)) {
String[] array = {"abc", "dfg", "hij"};
for(String elements : array) {
if(command.contains(elements) return;
yell(playerName + command.substring(5));
}

Note that I used the byte data type as I didn't want to waste that much memory for what I was doing. You would normally use an integer.

The for loop is also faster than the for each loop.