2016-02-23 20 views
0

嗨类我有一个机器人,我需要告诉它说前5.我有方法移动一定的次数前,我只需要得到它在我班上班。这里是方法:如何做的方法工作,我在Java中

public void moveNumOfTimes(int num) 
    { 
    //----------------------------------------------------------------------------------------------- 
     int i=0; 

     while(i<num) { 
     if (this.frontIsClear()){ // if the front is NOT clear the robot should not move, otherwise will collide into the wall 
      this.move(); 
     } 
     i++; // same as i=i+1; 
    } 
    //----------------------------------------------------------------------------------------------- 
    } 

如何在我的程序中输入?是这样吗?

moveNumOfTimes(int num); 

希望有人可以提供帮助。由于

+1

你称呼它,以同样的方式调用'fontIsClear()'或'移动()'方法,只是这次指定的次数作为参数(例如'moveNumOfTimes(5);')。如果你有这方面的问题,在继续你的项目之前,你应该阅读Web上的Java教程。 – Laf

+0

有很多很好的教程。它看起来像你想从命令行读取。给这篇文章读:http://alvinalexander.com/java/edu/pj/pj010005 – Joe

+0

我明白,但我的意思在命令行中输入它告诉它跑五次,而不是输入它的每一次我的希望它前进一定数量的步骤。 – Tom

回答

0

您应该使用扫描仪对象采取从控制台输入。

Scanner sc = new Scanner(System.in); 

你可以这样实现。

class Robot{ 

public static void main(String args[]){ 

Scanner sc = new Scanner(); 
int numOfSteps = sc.nextInt(); //This line takes a integer input from the user 

YourClassName r = new YourClassName(); 
//DO any initialization operations here 

r.moveNumOfTimes(numOfSteps); 

//Post movement operations come here 

} 

您可以了解更多关于扫描仪here

0

如何在我的程序输入?是这样吗?

moveNumOfTimes(int num); 

是的,你可以使用类似这样的东西,如果你试图从其他方法调用传递的命令。喜欢的东西:

public void Control(int moveNumber) { 
    ... some other code, do some other stuff... 
    moveNumOfTimes(moveNumber); //Here you are passing a parameter value to your original method; 
} 

或者你可以直接像其他方法控制它:

public void moveFive() { 
    moveNumOfTimes(5); 
} 

更可能的,但是,你不想硬编码的方法,而是直接通过调用原始的方法你的Main method

public static void main(String [ ] args) { 
    Robot r = new Robot(); 
    r.moveNumOfTimes(5); //Here you have moved your new robot! 
} 

如果你真的想获得幻想,期待与SystemScanner类工作,所以你可以提示用户来告诉机器人多少移动:

public static void main(String [ ] args) { 
     Robot r = new Robot(); 
     Scanner reader = new Scanner(System.in); 
     System.out.println("How far should the robot move?"); //Output to the console window 
     int input = reader.nextInt(); //Reads the next int value 
     r.moveNumOfTimes(input); //Calls your method using the scanned input 
}