Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/385.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将随机值设置为未分配/可选参数_Java_Parameters_Optional Parameters - Fatal编程技术网

Java 将随机值设置为未分配/可选参数

Java 将随机值设置为未分配/可选参数,java,parameters,optional-parameters,Java,Parameters,Optional Parameters,我正在构建一个平铺贴图生成器应用程序,我希望用户能够在构建贴图时将贴图的子区域设置为特定类型的平铺。 目前的实施方式如下: public boolean setArea(int bottomLeftX, int bottomLeftY, int subWidth, int subHeight, TerrainType aAreaType){ boolean areaOverflow = false; System.out.println("Subarea coords..

我正在构建一个平铺贴图生成器应用程序,我希望用户能够在构建贴图时将贴图的子区域设置为特定类型的平铺。 目前的实施方式如下:

public boolean setArea(int bottomLeftX, int bottomLeftY, int subWidth, int subHeight, TerrainType aAreaType){
    boolean areaOverflow = false;
        System.out.println("Subarea coords...     x,y:"+bottomLeftX+","+bottomLeftY+" width/height:"+subWidth+"/"+subHeight);
        for(int x=bottomLeftX;x<=bottomLeftX+subWidth-1;x++){
            for(int y=bottomLeftY;y<=bottomLeftY+subHeight-1;y++){
                if(x>=0 && y>=0 &&
                   x<this.getWidth() && y<this.getHeight()){
                    this.setTile(x, y, aAreaType);
                }
                else{
                    areaOverflow = true;
                }
            }
        }
        return areaOverflow;
    }
}
public boolean setArea(int-bottomLeftX,int-bottomLeftY,int-subWidth,int-subweight,TerrainType-aAreaType){
布尔区域溢出=false;
System.out.println(“分区坐标…x,y:+bottomLeftX+”,“+bottomLeftY+”宽度/高度:“+subWidth+”/“+subwhite”);
对于(int x=bottomLeftX;x=0&&

x您可以将参数定义为
Integer
s,而不是
int
s。这样您就可以为它们传递
null
值。在方法中,您可以检查这些参数中是否有任何参数是
null
,并根据这些检查的结果进行操作。

因为Java没有默认参数功能,一种方法是以伸缩方式重载方法:

请阅读评论,因为它们有一些解释

其思想是,参数较少的方法调用参数较多的方法,并为未接收到的参数生成默认(或随机)值。在链的末尾,调用接收所有参数并执行实际任务的方法


这种方法并不完美,在我的示例中,不可能有两个
someMethod(int)
,即一个接收一个
int
作为
param1
,另一个接收一个
int
作为
param2
。但有时这就足够了,特别是当您不需要所有可能的参数组合时。

如果出于任何原因将int更改为int不是一个选项(因此为null),这里有一个替代方案

重载方法,但仅使用用户必须显式提供的参数,并使用此方法内部的完整参数调用方法

简化示例:

public int myMethod(int a, int b, int c) {
  return a+b+c;
}

public int myMethod(int a) {
  return myMethod(a, (int)Math.random(),(int)Math.random());
}
至于你问的关于随机化枚举的部分,我会向你的枚举添加静态方法,例如,
randomize()
。如果你问的是这个方法的具体实现,那就另当别论了


返回
ENUM.values()(aAreaType==null){aAreaType=TerrainType.values()[random.nextInt(TerrainType.values().length)];}
public int myMethod(int a, int b, int c) {
  return a+b+c;
}

public int myMethod(int a) {
  return myMethod(a, (int)Math.random(),(int)Math.random());
}