Answer the question
In order to leave comments, you need to log in
JAVA, can you explain the strange for(: ); to me?
I would like to ask what is Noodle noodle in for (Noodle noodle : allTheNoodles) in this part of the code .
I understand it is something like "For all noodles in the array allTheNoodles". But I can't understand why there are two noodles here. What is the first word, and what is the second? One with a capital letter, the other with a small one.
Previously, when teaching, I only got acquainted with this type of for: for (int age:ages). And here is something that is not clear to me.
PS I apologize in advance for the easy questions, as a newbie, they don't seem obvious to me.
By the way, the code below does not show 3 classes that extend the Noodle class. It's Spaghetti, Ramen, Pho
class Noodle {
protected double lengthInCentimeters;
protected double widthInCentimeters;
protected String shape;
protected String ingredients;
protected String texture = "brittle";
Noodle(double lenInCent, double wthInCent, String shp, String ingr) {
this.lengthInCentimeters = lenInCent;
this.widthInCentimeters = wthInCent;
this.shape = shp;
this.ingredients = ingr;
}
public String getCookPrep() {
return "Boil noodle for 7 minutes and add sauce.";
}
public static void main(String[] args) {
Noodle spaghetti, ramen, pho;
spaghetti = new Spaghetti();
ramen = new Ramen();
pho = new Pho();
// Add your code below:
Noodle[] allTheNoodles = {spaghetti, ramen, pho};
for (Noodle noodle : allTheNoodles) {
System.out.println(noodle.getCookPrep());
}
}
}
Answer the question
In order to leave comments, you need to log in
Noodle noodle : allTheNoodles
Conventionally, it can be read as: the noodle variable in an array of Noodle[] objects.
This is a type of for each loop, where you iterate through each object contained in the Noodle[] array
, and you can use the noodle variable to refer to the corresponding object in the loop. Those. in each iteration this variable will be assigned the next object contained in the array
The above answers didn't show one key feature that is available at the moment, which is usage var
in a for
.
There is absolutely no need to explicitly define the type of a variable, you can just get away with the following construct:
Moreover, life is effectively simplified when you move from arrays to collections and streams (streams api), in which case you have direct access to lambdas and parallelization :for (var noodle : allTheNoodles)
Noodle[] allTheNoodles = {spaghetti, ramen, pho};
Stream.of(allTheNoodles).parallelStream().forEach(noodle -> { System.out.println(noodle.getCookPrep()) });
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question