【问题标题】:Having trouble returning an object [duplicate]返回对象时遇到问题[重复]
【发布时间】:2015-01-30 15:26:31
【问题描述】:

这是我的程序:

Public class SimpleRGB
{
    //Instance variables

    private int width, height;
    private int[][] red = new int[10][10];
    //same for green/blue

    public SimpleRGB(int aWidth, int aHeight)
    {
        //...
    }

    //Some methods

这是给我带来麻烦的方法。在这种方法中,我应该创建一个新图像(简单的 rgb 对象),使用嵌套的 for 循环将新的简单 rgb 的红色 D 数组设置为这个简单 rgb 的红色 2D 数组(不确定我是否有'不正确),在同一个循环中将绿色和蓝色设置为 0(认为我已经正确完成了),然后返回新的简单 rgb 对象。我对此很陌生,所以我不确定如何返回我的简单对象也会返回我在 for 循环中设置的数据,我也不相信我正在正确创建/返回简单的 rgb。任何帮助将不胜感激!谢谢。

    Public SimpleRGB getRedImage()
    {

        SimpleRGB redImage = new SimpleRGB(); //Completely lost here. Not sure why but Java won't let me use "new: here. Also I'm confused as to how the data from the for-loop will even bee associated with this objectd       

        for (int i = 0; i < width; i++)
        {
            For (int j  0; j < height; j++)
            {
                red[i][j] = ?? //some code here to set red value of new object to red value
                green[i][j] = 0; //set to 0 b/c we only want red color
                blue[i][j] = 0; //set to 0 b/c we only want red color
            }
        }

        Return redImage(); //not sure if this is correct/if "()" are needed

【问题讨论】:

  • 这看起来与您之前在提供 2 个答案时提出的问题相同:stackoverflow.com/questions/28223214/…
  • 是的,基本上是这样,我试图改写它,以明确我遇到的问题。
  • 您不需要在 return 语句中使用“()”,从代码来看,我不确定 redImage 是如何链接到红色绿色和蓝色数组的。所以目前看来,您返回的对象与您在 for 循环之前创建的对象完全相同。
  • 如果答案不适用于您的原始问题,我建议您更新原始问题以进行澄清,并说明它们为什么不起作用。

标签: java object for-loop


【解决方案1】:

以下是对您的方法的一些快速修复。首先,您需要在SimpleRGB() 调用中添加两个int 参数,即SimpleRGB(int,int) 秒,我的目标是for 循环中该新对象的数组。

Public SimpleRGB getRedImage()
{

    SimpleRGB redImage = new SimpleRGB(int,int);     

    for (int i = 0; i < width; i++)
    {
        For (int j  0; j < height; j++)
        {
            redImage.red[i][j] = ??;  
            redImage.green[i][j] = 0;
            redImage.blue[i][j] = 0;
        }
    }

    Return redImage; //removed the ()
}

【讨论】:

  • 您基本上是正确的,谢谢!我只需要进行一些更改: SimpleRGB redImage = new SimpleRGB(width, height);在 for 循环中: redImage.setRed(i, j, getRed(i, j));和 redImage.setRed(i, j, 0);蓝色和绿色。
猜你喜欢
  • 1970-01-01
  • 2020-10-25
  • 2016-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多