2016-02-23 17 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 
}