【问题标题】:How to send random class to the new method as an argument如何将随机类作为参数发送到新方法
【发布时间】:2021-10-01 19:19:29
【问题描述】:

如何将随机类作为参数发送给新方法?

package practice;

import java.util.Random;

public class test {

    public static void main(String[] args) {
        Random generator= new Random(seed);
        
        fillMatrixRandom(generator);
        
        
        public static void fillMatrixRandom(int generator) {

    }

}

【问题讨论】:

  • generator 的类型是 Random,而不是 int.,它应该是 fillMatrixRandom(Random generator)。
  • 或致电generator.nextInt()。
  • 或者调用 generator.nextInt()。
  • 或者调用 generator.nextInt()。怎么称呼它
  • 我听不懂

标签: java arrays eclipse random methods


【解决方案1】:

这个方法应该是这样的。必须更改数据类型。

public static void fillMatrixRandom(Random generator) {

    }

【讨论】:

    【解决方案2】:

    你想把什么传递给方法?

    -> 如果你想传递一个随机的int 值,那么你应该调用fillMatrixRandom() 方法为fillMatrixRandom(generator.nextInt());:

    package practice;
    
    import java.util.Random;
    
    public class test {
        private static int seed = 42;
    
        public static void main(String[] args) {
            Random generator = new Random(seed);
            
            fillMatrixRandom(generator.nextInt());
        }
        public static void fillMatrixRandom(int generator) {
    
        }
    }
    

    -> 如果要将随机生成器传递给方法(使其可以多次调用generator.nextInt()),则需要将方法fillMatrixRandom()声明为void fillMatrixRandom(Random generator) { /* ... */ }

    package practice;
    
    import java.util.Random;
    
    public class test {
        private static int seed = 42;
    
        public static void main(String[] args) {
            Random generator = new Random(seed);
            
            fillMatrixRandom(generator);
        }
        public static void fillMatrixRandom(Random generator) {
    
        }
    }
    

    【讨论】:

    • 非常感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-28
    • 1970-01-01
    • 2023-03-15
    相关资源
    最近更新 更多