Issue
I’m working on creating some Java methods to make writing code quicker and more efficient, and right now I’m trying to make a simple loop I’m calling "repeat."
It will work something like this:
repeat(number of times to repeat) {
code to be repeated
}
So for example:
repeat(3) {
System.out.println("hi")
}
Would display:
hi
hi
hi
How can I make a method/function like this? I also need it to work as a nested loop.
Solution
repeat(3) {
System.out.println("hi")
}
- Java does not support this grammar. If you want to support this via the grammar, try another language that supports closures
- Another way you can try, Java can implement it by lambda
public static void main(String[] args) {
repeat(3, () -> {
System.out.println("hi");
});
}
public static void repeat(int count, Runnable function) {
for(int i = 0; i < count; i++) {
function.run();
}
}
Answered By – math-chen
Answer Checked By – Marie Seifert (BugsFixing Admin)