如何按用户输入的数字移动机器人?

时间:2017-01-16 14:43:01

标签: java

我使用drjava-stable-20120818-r5686进行编码

    class Assignment2
    {
     public static void main(String[] args)
         {
      World barney=new World(20,20);
      Robot bob=new Robot();
      barney.addBeeper(6,4);
      barney.add(bob,4,4,"north");
      System.out.println("1. Turn left from current direction.");
     System.out.println("2. Turn right from current direction.");
     System.out.print("Enter Choice: ");
     int choice=Console.readInt();

     if(choice==1)
     {
     bob.turnLeft();
     }
     else
     {
     bob.turnLeft();
     bob.turnLeft();
     bob.turnLeft();
     }

     System.out.println("1. Move Forward Once.");
     System.out.println("2. Move Forward Twice.");
     System.out.println("3. Move Forward X Times.");
     System.out.println("Enter Choice: ");
     int choice2=Console.readInt();
     if(choice2==1)
     {
       bob.move();
     }
     if(choice2==2)
     {
        bob.move();
         bob.move();
     }
     else
     {
       System.out.println("Enter X: "); //dont know what to do next :(
    }
    [enter image description here][1]`

**我们的老师说使用循环(while)来做,但我不确定如何 **

2 个答案:

答案 0 :(得分:1)

类似的东西:

System.out.println("Enter X: ");
int x =Console.readInt();
while(x>0) {
         bob.move();
         x--;
         }

答案 1 :(得分:0)

查看While Loop的Oracle文档,关于语法的部分如下所述:

  

while(表达式){        声明(S)   }

使用此代码,以下代码应解决您的问题......

int X=Console.readInt();
while(X-->0){ bob.move();}