芬奇机器人-如何循环特定代码行? (Java)

时间:2019-03-01 02:37:24

标签: java eclipse robot finch

我对编码完全陌生,不知道我在做什么。我有一个用于Finch机器人的代码,可以使它左右移动,但是如何使这个简单的过程循环3次?另外,是否可以实施代码来询问用户他们希望产品循环多少次?

很抱歉,这似乎是一个愚蠢的问题。我到处都看过,还不太了解如何正确循环代码。我要循环的代码发布在下面。

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 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

第一种方法:使用for循环

 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);
 }

第二种方法:使用while循环

          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--; 

       }

第三种方法:使用do-while循环

           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);