传递Random对象作为参数的麻烦

时间:2015-05-19 20:49:52

标签: java syntax parameters

我无法将随机对象作为参数传递。

我制作了一个新文件来测试它,我也遇到了同样的错误。谁能告诉我这有什么问题?

import java.util.*;
public class Practice {
  public static void main(String[] args) {
    Random r = new Random(1234);
    Spring (Random r);
  }

  void Spring (Random r) {
    r.nextInt(20);
  }
}

我得到的错误是:

/tmp/Practice.java:5: error: ')' expected
    Spring (Random r);
                  ^
/tmp/Practice.java:5: error: illegal start of expression
    Spring (Random r);
                    ^
2 errors

2 个答案:

答案 0 :(得分:1)

你有几个问题......

这就是你应该做的事情(见解释评论):

    public static void main(String[] args) {
        Random r = new Random(1234);
        //don't need Random here
        //also call static method
        Practice.Spring (r);
}
  //since you are calling a static method, you need to declare it static
  //also it's good practice to add the methods access modifier.
  private static void Spring (Random r) {
      r.nextInt(20);
}

答案 1 :(得分:0)

要调用Spring(...),首先必须创建类的实例。要实现这一点,您必须调用构造函数:

Practice myPractice = new Practice();

在此之后你可以调用你的Spring方法:

myPractice.Spring(r); //Random must be left out at this place - only when declaring the function interface