从另一个类和方法返回类中的值

时间:2013-06-16 16:31:22

标签: java class variables methods

请注意,我是Java新手。我有一个类和一个方法在这个类帽子计算一些值,我想在第一个类中返回它们。我有一个代码,但它返回0.

这是在课堂上计算值

public class ImageProcessing{
int i,j;
int R[][]=new int[640][320];
int G[][]=new int[640][320];
int B[][]=new int[640][320];


public double meanR[]=new double[320];
public double meanG[]=new double[320];
public double meanB[]=new double[320];
public double varianceR[]=new double[320];
public double varianceG[]=new double[320];
public double varianceB[]=new double[320];
public double skewnessR[]=new double[320];
public double skewnessG[]=new double[320];
public double skewnessB[]=new double[320];

public double round(double value){
    //  int decimalPlace = 2;

    BigDecimal bd = new BigDecimal(value);
    bd = bd.setScale(2,BigDecimal.ROUND_UP);
    return (bd.doubleValue());
}

public void Mean(Bitmap image){

    int width = image.getWidth();
    int height = image.getHeight();
    int pixel = 0;


    for (i=0; i<width;i++){
        for (j=0; j<height; j++){
            pixel = image.getPixel(i,j);
            R[i][j] = Color.red(pixel);
            G[i][j]= Color.green(pixel);
            B[i][j] = Color.blue(pixel);


            meanR[j]=meanR[j]+R[i][j];
            meanG[j]=meanG[j]+G[i][j];
            meanB[j]=meanB[j]+B[i][j];
        }
    }

在主要课程中我有:

    method.Mean(rescaledBitmap1);

    meanR1=method.meanR;
    meanG1=method.meanG;
    meanB1=method.meanB;
    System.out.println(meanR1);

2 个答案:

答案 0 :(得分:1)

您必须在方法定义中指定要返回的内容,并使用关键字return实际返回值:

public int sum(int a, int b){
 int result = a + b;
 return result;
}

您已将Mean()声明为void public void Mean(Bitmap image),因此它不返回任何值。

此外,您只能返回1个变量,因此您应该将这3个值放在某种数组中,或者创建一个新类并将变量封装在一个对象中。这是一个例子:

public class MeanResult(){
private double meanR[]=new double[320];
private double meanG[]=new double[320];
private double meanB[]=new double[320];
//Maybe declare more stuff here

 public MeanResult(Bitmap image){
  //... code n stuff here to calculate width, height and pixel
 }
 public double getMeanR(){ return this.meanR[]; }
 public double getMeanG(){ return this.meanG[]; }
 public double getMeanB(){ return this.meanB[]; }
}

你可以像这样使用它:

MeanResult mean = new MeanResult(image);
meanR1=mean.getMeanR();
meanG1=mean.getMeanG();
meanB1=mean.getMeanB();

答案 1 :(得分:0)

方法mean(Bitmap image)void。要让它返回某些内容,您必须将void更改为它将返回的内容,并在方法return变量的末尾更改。

示例:

public int add(int x, int y)
{
    return x + y;
}

然后,如果您拨打add(1,2),则其值为3.

相关问题