[SOLVED] How can I create a method in Java to create a new loop type?

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")
}
  1. Java does not support this grammar. If you want to support this via the grammar, try another language that supports closures
  2. 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)

Leave a Reply

Your email address will not be published.