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
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'm studying for a Java certification and on one of the mock exams I saw a very odd implementation of For loop. The exercise showed the following syntax :
for (Days d: Days.values());
At the beginning, I thought that it was a syntax error, since I always knew that the syntax for the "For loop" requires curly braces or, if there is only one instruction to iterate we can skip the curly braces and set our statement aligned just after the loop.
-- Since I haven't seen before a For loop ending with semicolon ";".--
Then I tried to find some documentation about it, but unfortunately I could not find any explanation why is a legal code declaration. Only references to the following syntax:
The syntax of enhanced for loop is:
for(declaration : expression)
{
//Statements
}
The odd thing is that after all of this, I tested my code and surprisingly it compiled and ran properly. Then, based on some tests that I did (playing with the code), I discovered that it seems that the ";" works like a For loop empty but with curly braces, so, any instruction after it, it is executed only one time. (As if the code where out of the loop). But I'm not sure if this is the right interpretation of the semicolon on the enhanced for loops.
Please see the complete example:
package com.TestDays;
public class TestDays {
public enum Days { MON, TUE, WED};
public static void main(String[] args) {
int x = 0;
*for (Days d: Days.values());*
Days[] d2 = Days.values();
System.out.println(d2[2]);
}
}
Does anyone knows why this syntax is allowed?
Thank you.
https://docs.oracle.com/javase/specs/jls/se7/html/jls-18.html
A for loop is defined as:
for ( ForControl ) Statement
; is a valid statement in Java, as is a block of statements. Not something you see often with this form of loop, but you can do things like:
int i = 2;
for(; i < 100; i*=2);
// i is now the smallest power of two greater than 100
Please note that in the documentation only mention the following syntax:
The syntax of enhanced for loop is:
for(declaration : expression)
{
//Statements
}
The "documentation" quoted your question comes from a page on TutorialsPoint (as seen by me on 2016-05-22). I'm not going to link to it, but assuming they have not corrected it (yet), you should be able to find it using a Google phrase search.
This is NOT the official documentation. The only official documentation for Java is the documentation written by Oracle (and previously Sun Microsystems) employees and published by these organizations.
TutorialsPoint has no standing. In this case, they have simply gotten the Java syntax wrong.
According to the Java 8 JLS, the real Java syntax for the enhanced for loop is1
EnhancedForStatement:
for ( {VariableModifier} UnannType VariableDeclaratorId : Expression )
Statement
EnhancedForStatementNoShortIf:
for ( {VariableModifier} UnannType VariableDeclaratorId : Expression )
StatementNoShortIf
where Statement and StatementNoShortIf include the empty statement; i.e. a bare semi-colon.
1 - The grammar rules are quoted from the Java 8 grammar. The "no short ifs" variant is about disambiguating nested if statements, and is not relevant here. In the Java 7 JLS, there are two versions of the grammar in the spec, one with the variants and one without them.
The documentation that you read is not the official documentation, since the authors would have written:
The enhanced for statement has the form for (declaration : expression) statement
This is because the braces are not needed.
A single semicolon forms a so-called _ empty statement_, and that makes your code snippet syntactically valid.
There are 3 main different ways a for-loop or enhanced for-loop can be created in Java:
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
for (int i = 0; i < 5; i++) System.out.println(i);
for (int i = 0; i < 5; i++);
These 3 loops are equivalent to:
For every time i is less than 5, do whatever is between {} and increment its value by one.
For every time i is less than 5, print i and increment its value by one.
For every time i is less than 5, increment its value by one.
Its not a matter of, "why doesn't it fail", its more, "what the for-loop is being told to do".
Specifically, WHY it doesn't fail, is the way the for-loop syntax is laid out. This was explained very well in Stephen C's answer:
According to the Java 8 JLS, the real Java syntax for the enhanced for loop is
EnhancedForStatement:
for ( {VariableModifier} UnannType VariableDeclaratorId : Expression )
Statement
EnhancedForStatementNoShortIf:
for ( {VariableModifier} UnannType VariableDeclaratorId : Expression )
StatementNoShortIf
As you can see, Statement refers to any valid statement, which includes the usage of ;, as ; is a valid "Statement". Because this is allowed, there is no reason why it should fail in any case.
Infact, another way to interpret for (int i = 0; i < 5; i++); would be:
"For every time i is less than 5, run statements, and increment its value by one."
Same rules can be applied to:
for (Integer i : ints) {
System.out.println(i);
}
for (Integer i : ints) System.out.println(i);
for (Integer i : ints);
I am trying to find on a Vector how many indexes start with a given letter or number.
I've tried vector.indexOf("A"); and vector.lastIndexOf("A"); but of course they are "useless" for what I am trying to do because those try to find a position that only have "A" and nothing else.
I wanted to know if there is a Java method to do this or if I need to do it "by myself", if so, a little guiding on the how-to process would be thanked.
If you do not want to (or can) use streams or lambdas you can also use this little loop here:
int count=0;
for (int i = 0; i < vec.size(); i++) {
count = vec.get(i).charAt(0)=='A' ? count+1 : count;
}
No big thing, just checking each element if it starts with A and then counting up.
In Java8 you can use Streams to access functional-style operations such as filter() and count(). Use the stream() method to get a Stream on your collection.
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);
}
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.