2017-09-30 49 views
-1

我想我得到了第一個方法正確,我只是不知道如何去調用我的第二個方法中的第一個方法,並使用種子。當使用random.nextInt時,我如何使用種子部分是我在這方面最少理解的部分。我如何打電話和方法並插入種子?

public class Compass { 
    // TODO - write your code below this comment. 
    // You will need to write two methods: 
    // 
    // 1.) A method named numberToDirection, which 
    //  takes an int and returns a String representing 
    //  either a direction, or the string 
    //  "Out of range: " + x 
    //  ...where x is the input int 
    // 
    // 2.) A method named randomDirection, which 
    //  takes a long and returns a String. 
    //  The long should be used as a seed value with 
    //  which to generate a random number between 
    //  0-7, inclusive. This random number should 
    //  then be used as a parameter to a call to 
    //  numberToDirection. randomDirection should 
    //  return the result of the call to 
    //  numberToDirection. 
    //  To be clear, randomDirection MUST CALL 
    //  numberToDirection! 
    public static String numberToDirection(int x) { 
     switch (x) { 
     case 0: 
      System.out.println("North"); 
     case 1: 
      System.out.println("Northeast"); 
     case 2: 
      System.out.println("East"); 
     case 3: 
      System.out.println("Southeast"); 
     case 4: 
      System.out.println("South"); 
     case 5: 
      System.out.println("Southwest"); 
     case 6: 
      System.out.println("West"); 
     case 7: 
      System.out.println("Northwest"); 
     default: 
      System.out.println("Unknown direction" + x); 
     } 
    } 

    public static String randomDirection(long seed) { 
     switch (numberToDirection(random.nextInt(7) + 1)) { 

     } 
    } 

右上方這裏是我卡住的地方。

// DO NOT MODIFY main! 
    public static void main(String[] args) { 
     Scanner input = new Scanner(System.in); 
     System.out.print("Enter seed: "); 
     long seed = input.nextLong(); 
     System.out.println("Random direction: " + randomDirection(seed)); 
    } 
} 
+0

您有** NOT **第一個方法正確。它必須返回一個字符串。 – progyammer

+0

因此,而不是system.out.println我應該使用返回「...」的權利? –

+0

你什麼時候初始化隨機變量? Random類有一個構造函數,除了需要一個很長的種子參數的默認值 – FattySalami

回答

0

你必須創建一個Random對象,並提供與seed價值爲出發點,爲你的隨機數生成器的構造。之後,您可以簡單地致電nextInt()

public static String randomDirection(long seed) 
{ 
    Random r = new Random(seed); 
    int direction = r.nextInt(8); 
    String dirAsString = numberToDirection(direction); 
    // work with dirAsString here... 
} 
相關問題