Finch Robot - How do I loop specific lines of code? (Java)

248 Views Asked by At

I am completely new to coding and have no clear idea what I am doing. I have a code for my Finch robot that simply makes it move left and right, but how do I make this simple process loop for three times? Additionally, can a code be implemented to ask the user how many times do they want the product to loop?

Sorry if this seems like a stupid question. I've looked everywhere and don't quite understand how to loop a code properly. The code that I want to loop is posted below.

public static void main(final String[] args)
       {
          Finch myFinch = new Finch();

          myFinch.setLED(Color.green);
          myFinch.setWheelVelocities(180, 0, 750);
          myFinch.setWheelVelocities(100, 100, 1500);

          myFinch.setLED(Color.red);
          myFinch.setWheelVelocities(0, 180, 850);
          myFinch.setWheelVelocities(180, 180, 1500);

          myFinch.quit();
          System.exit(0);
          }             
2

There are 2 best solutions below

0
Nilanjan Bhadury On BEST ANSWER

First Approach: Using for loop

 public static void main(final String[] args)
           {
              Finch myFinch = new Finch();
              Scanner sc = new Scanner(System.in);
              System.out.println("How many times?");
              int noOfTimes = sc.nextInt();

            for(int movement=0; movement < noOfTimes; movement++){ 
              myFinch.setLED(Color.green);
              myFinch.setWheelVelocities(180, 0, 750);
              myFinch.setWheelVelocities(100, 100, 1500);

              myFinch.setLED(Color.red);
              myFinch.setWheelVelocities(0, 180, 850);
              myFinch.setWheelVelocities(180, 180, 1500);
           }
              myFinch.quit();
              System.exit(0);
 }

Second Approach: Using while loop

          Scanner sc = new Scanner(System.in);
          System.out.println("How many times?");
          int noOfTimes = sc.nextInt();

  while(noOfTimes > 0){ 

          myFinch.setLED(Color.green);
          myFinch.setWheelVelocities(180, 0, 750);
          myFinch.setWheelVelocities(100, 100, 1500);

          myFinch.setLED(Color.red);
          myFinch.setWheelVelocities(0, 180, 850);
          myFinch.setWheelVelocities(180, 180, 1500);
          noOfTimes--; 

       }

Third Approach: Using do-while loop

           Scanner sc = new Scanner(System.in);
          System.out.println("How many times?");
          int noOfTimes = sc.nextInt();

       do{

          myFinch.setLED(Color.green);
          myFinch.setWheelVelocities(180, 0, 750);
          myFinch.setWheelVelocities(100, 100, 1500);

          myFinch.setLED(Color.red);
          myFinch.setWheelVelocities(0, 180, 850);
          myFinch.setWheelVelocities(180, 180, 1500);
          noOfTimes--; 

       }while(noOfTimes > 0);
0
Matt On