The Soul
Moderator
Number of posts : 8
Points :
Registration date : 2009-12-31
|
Subject: Using the for/enhanced for loop Thu Dec 31, 2009 12:58 am |
|
|
The purpose of the tutorial is to learn about the for loop, and some examples of how it works.
Simple for statement: - Code:
-
for(int i = 0; i < 10; i++) { System.out.println("Number: " + i) ; } If you were to run this, it would print out 'Number: 0-9' in the command prompt.
This is the declaration of this integer. We're using 'i' as the iterator because it's short and easy: - Code:
-
int i = 0; This means that if 'b' were to be greater than 10, the loop will conclude. All this does is basically check if 'i', the iterator is less than 10, and if it is, the loop will continue: - Code:
-
i < 10; All the below means is 'i' will go up by 1 until it reaches 10. - Code:
-
i++
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: - Code:
-
if (command.equalsIgnoreCase("master") { for (int i = 0; i < 24; i++) { 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.
- Code:
-
if(command.equals("yell")) { String[] array = {"abc", "dfg", "hij"}; String msg = command.substring(5); for(int i = 0; i < array.length; i++) { if(msg.contains(i)) return; yell(playerName+": "+msg); } Or you could use the for each loop, also known as the enhanced for loop.
- Code:
-
if(command.equals("yell")) { String[] array = {"abc", "dfg", "hij"}; String msg = command.substring(5); for(String elements : array) { if(msg.contains(elements)) return; yell(playerName+": "+msg); } The for each loop is great for grabbing every element in an array. It is also faster than the for loop.
|
|