Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Nicholas Brigham
780 PointsWhy do I "need" to use an enhanced for-loop for this Java Objects objective?
Traditional for-loops are much easier for me to understand and they do the same thing. From what I have read, enhanced for-loops are also somewhat limited in their abilities compared to traditional for-loops. If I can get the objective done with a traditional for-loop then what difference does it make?
2 Answers
Billy Trivett
642 PointsFor the average developer, if there is an easier and cleaner way to do something, then why not?
I wouldn't say that enhanced for loops are "limited." They are made so that you can have clear syntax while looping through all the data in a list.
There isn't too much difference between using regular and enhanced, but try to practice using it so you know how because other developers might find it easier to use enhanced.
Also, what do you find hard to understand about enhanced for loops?
Timothy Boland
18,237 PointsI myself am having a hard time trying to convert the following to an enhanced for loop:
String tiles = "letters";
public int getCountOfLetter(char letter) {
int countOfLetter = 0;
for (int i=0; i < tiles.length(); i++)
{
if (tiles.charAt(i) == letter)
{
countOfLetter++;
}
}
return countOfLetter;
}
}
getCountOfLetter(t);
UPDATE Nevermind....I figured it out:
public int enhancedGetCountOfLetter(char letter) {
int countOfLetter = 0;
for (char x : tiles.toCharArray()) {
if (x == letter) {
countOfLetter++;
}
}
return countOfLetter;
}
}
Timothy Boland
18,237 PointsHey Bro,
I agree...ive always preferred to used the standard for loop, but here is the answer to help you figure it out:
I included a link to a video which helps explain it a little better too:
Java Programming Tutorial - 31 - Enhanced for Loop
String tiles = letters;
public int getCountOfLetter(char letter) {
int countOfLetter = 0;
for (char x : tiles.toCharArray()) {
if (x == letter) {
countOfLetter++;
}
}
return countOfLetter;
}
}
AJ Longstreet
Treehouse Project ReviewerAJ Longstreet
Treehouse Project ReviewerIf it's hard for you to understand now, it's telling you that you should be looking to fill in that knowledge gap. It will help a lot as you progress into harder concepts such as lambdas and streams.