This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
java for loop syntax
for (File file : files){
...body...
}
What mean in for loop condition this line?
This is java for-each (or) enhanced for loop
This means for each file in files array (or) iterable.
for (File file : files) -- is foreach loop in Java same as saying, for each file in files. Where files is an iterable and file is the variable where each element stored temporarily valid withing the for-loop scope. See http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
This says for-each file in a set fo files do ... (body)
Read about The For-Each Loop for more details. The examples in the link where great.
- This form of loop came into existence in Java from 1.5, and is know as For-Each Loop.
Lets see how it works:
For Loop:
int[] arr = new int[5]; // Put some values in
for(int i=0 ; i<5 ; i++){
// Initialization, Condition and Increment needed to be handled by the programmer
// i mean the index here
System.out.println(arr[i]);
}
For-Each Loop:
int[] arr = new int[5]; // Put some values in
for(int i : arr){
// Initialization, Condition and Increment needed to be handled by the JVM
// i mean the value at an index in Array arr
// Its assignment of values from Array arr into the variable i which is of same type, in an incremental index order
System.out.println(i);
}
Related
I am trying to make a little game on my own to get used to Java and I just had a problem with LinkedList Index. I found a way to patch my problem but I still don't understand why my first solution is not working. This code:
for (int i=0; i <= PlanetList.size(); i++)
{
g.drawImage(PlanetList.get(i).planetImage, PlanetList.get(i).xPos, PlanetList.get(i).yPos);
}
Gave me a java.lang.IndexOutOfBoundsException but this code:
for (int i=1; i <= PlanetList.size(); i++)
{
g.drawImage(PlanetList.get(i-1).planetImage, PlanetList.get(i-1).xPos, PlanetList.get(i-1).yPos);
}
The thing is ... my index start at 0 in both case. Why does the first gives me an Error?
Your last index in the first example is going above the allowed index range. For e.g., if the size of the list is 10, the allowed index range is [0 9]. In your first loop, it goes up to 10 (i <= PlanetList.size()). Change the terminal condition to i < PlanetList.size() to fix your issue.
The alternate is to use no indices to access elements in your list as #GhostCat has suggested:
for (Planet planet : PlanetList) {
g.drawImage(planet.planetImage, planet.xPos, planet.yPos);
}
This is called for-each loop in Java
The other solution is to simply use the index-free version to iterate "collections" that was introduced years ago:
for (Planet planet : PlanetList) {
g.drawImage(planet.planetImage, planet.xPos, planet.yPos);
As a nice side effect, that also eliminates the code duplication that you had in your example.
And while we are at it: you are somehow violating the "tell dont ask" principle. Meaning: you are asking your planet object to give all the details you need to draw it. In good Object Oriented designs, you avoid that. Instead, you tell objects to do something. In other words: you could change your planet class to
public void drawWith(Graphics g) { ...
With that the above code can be rewritten as:
for (Planet planet : ... ) {
planet.drawWith(g);
YOU are getting the Out of bounds error because the variable i declared in the for loop is running for less than equal to condition of planetlist size as i starts from zero it will go till the linked list size but since you have given less than equal to it goes in the loop one more time therefore out of bounds exception .Just change the for loop condition to i less than linked list size it will work
I have a question about for loops in java. I understand how for loops work an using the format :
for(initialize variable : condition : counter){}
My problem is in one of my lectures it says:
for(String s : str){.....}
How come this doesn't need a counter?
What is str?
This is an enhanced for loop, or a "for each" loop. It iterates over all the elements of str, which is probably a Collection of Strings in your example, or an Array of Strings.
Read this for more details.
For example, instead of writing this:
for (int i = 0; i < myArray.length; i++) {
System.out.println(myArray[i]);
}
you can write its equivalent:
for (int myValue : myArray) {
System.out.println(myValue);
}
First of all replace : with ; in the first for loop like this(you have used wrong syntax)
for(initialize variable ; condition ; counter){}
and the second one is the enhanced for loop,
for(String s : str){.....}
quite handy in case of the collections,It does not require any counter because it runs till it reaches the last element in the collection provided to it(In this case str is that collection)
See this to learn more about it What is the syntax of enhanced for loop in Java?
It is an enhanced for loop that iterates through every element in the Collection. It doesn't stop until it is has hit the last element or encounters a break;.
Your definitive source for this sort of questions is the Java Language Specification. In this particular case:
http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.14
A more friendly source may be found in the official Java Tutorials, in this case:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
This question already has answers here:
random number generator from a range for continuos analysis
(2 answers)
Closed 9 years ago.
I need to generate a list of non repeating random numbers between 0 and 1000 as efficiently as possible in Java. I only have 2 ideas right now and would like to know if there are any other better ideas and if not which I the following ideas should I use?
generate a random number r between 0 and 1000 and add it to another array called randomArray[r] at index r
generate another random number and check if randomArray[r] isn't already storing a previously generated random number
keep going until I'm done
generate an array and fill its element with its index
shuffle it like crazy(also, how can I do this efficiently?)
use the elements value in the array starting from the beginning.
Thanks!
java.util.Collections.shuffle method shuffle a List with equal likelihood. create a List and add value from 0 to 1000. Then use this method to shuffly the List.
List l = new ArrayList();
for(int i = 0; i <= 1000; i++)
l.add(i);
Collections.shuffle(l);
Now the list contains the shuffled values.
Try using a LinkedHashSet<Integer> (see documentation).
A regular HashSet<Integer> stores a set of Integers efficiently: placing a new number and checking if a number is already present is done in constant time (when storing the numbers in an array, as you mentioned, these lookups take linear time to check).
Now, since you say you want a list of numbers, we use a LinkedHashSet<Integer> which has all the properties of the regular HashSet<Integer>, and also garantees that if you loop over the elements, you will always iterate through them in the same order.
The code would look something like this:
Set<Integer> randomNumberList = new LinkedHashSet<Integer>();
int r;
// Make sure the number is not present in the list, and then add it:
do {
r = ... // Generate your next random number
} while( randomNumberList.contains(r) );
// At this point, we know r is not in the list, so add it:
randomNumberList.add(r);
// Do the previous as many times as you want.
// Now, to iterate over the list:
for(Integer number : randomNumberList) {
// Do something...
}
Note that the do-while loop is necessary if you want to make sure you actually add a number to the list.
i have this code, and i would like to know what the ":" mean in the function
Element[][] grid = readFile();
for (Element[] ea : grid) {
for (Element e : ea)
System.out.print(e.getChar());
System.out.println();
In terms of a language equivalent, you can think of it as the word "in". You can read it as "for each Element 'e' in 'ea'".
Here's the documentation on that type of loop: http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
When : is used in for, it acts as a for-each loop. Each iteration, the variable after the colon is assigned to the next value in the array.
int[] arr = {1,2,3,4};
for ( arr : num ) {
System.out.print( num + " " );
}
// prints "1 2 3 4 "
It's a for-each comprehension for Collections and Array. It's same as some languages like Python provide in functionality. So when you see a : in a for loop, read as in. For more details see this http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
In your case it's like for ea in grid.
This type of loop is called a 'for-each' loop. The colon (:) is read as 'in'. Basically, this type of for loop is used with collections.
It could be read as:-
for each element x in collection Y{
//do something
}
Here, in each iteration, the element x refers to the respective elements in Collection Y. i.e, in first iteration, x will be Y[0], in second iteration, x will be y[1], so on and so forth till the end.
The advantage is that condition checking and all those stuff need not be written explicitly. It is especially useful when iteration elements in a collection sequentially till the end. This makes iterating over collections quite easier. It is easier than making use of iterators.
In your code, each element of the two dimensional array 'ea' is printed, using a nested for-each loop. Outer loop iterates over each row (a single dimensional array), and inner loop iterates over each element in the respective row.
Refer these:-
For-each loop
Related question in stackoverflow
This is the new enhanced for loop.
You can read it out loud as for each Element ea in grid. It iterates over the elements in grid.
Here is a nice tutorial .
It's simply a divider between the temporary variable and the Iterable or array.
It's called a foreach loop, and basically means:
"For each element ae in Iterable grid, do {...}"
Read more here: The For-Each Loop
Iterable being an array or a list, for example.
Basically, I am trying this, but this only leaves array filled with zeros. I know how to fill it with normal for loop such as
for (int i = 0; i < array.length; i++)
but why is my variant is not working? Any help would be appreciated.
char[][] array = new char[x][y];
for (char[] row : array)
for (char element : row)
element = '~';
Thirler has explained why this doesn't work. However, you can use Arrays.fill to help you initialize the arrays:
char[][] array = new char[10][10];
for (char[] row : array)
Arrays.fill(row, '~');
From the Sun Java Docs:
So when should you use the for-each loop?
Any time you can. It really beautifies your code. Unfortunately, you cannot use it everywhere. Consider, for example, the expurgate method. The program needs access to the iterator in order to remove the current element. The for-each loop hides the iterator, so you cannot call remove. Therefore, the for-each loop is not usable for filtering. Similarly it is not usable for loops where you need to replace elements in a list or array as you traverse it.
This is because the element char is not a pointer to the memory location inside the array, it is a copy of the character, so changing it will only change the copy. So you can only use this form when referring to arrays and objects (not simple types).
The assignment merely alters the local variable element.