使用Java创建带有输入的for循环

时间:2013-10-30 23:23:17

标签: java image loops for-loop pixel

这是我的代码:

 public static Picture modifyPicture (Picture p, int value)
 {
  // get width and height of the picture
  int width = p.getWidth();
  int height = p.getHeight();
  System.out.println ("Picture has width of " + width + 
                      " and height of " + height);

  Picture p2 = new Picture (width, height*value);

  int x = -1;
  int y = -1;

  for  ( x = 0 ; x < width ;  ++x )
  {
    for ( y = 0 ; y < height ; ++y )
    {
     Pixel pixel1 = p.getPixel (x,y);
     Color c1 = pixel1.getColor();

     Pixel pixel4 = p2.getPixel (x, y);
     pixel4.setColor( c1 );

     Pixel pixel5 = p2.getPixel (x, y + 1 * height);
     pixel5.setColor( c1 );

     Pixel pixel6 = p2.getPixel (x, y + 2 * height);
     pixel6.setColor( c1 );
   }
 }
 return p2; 
}  // end of method
嘿伙计们,这似乎是一个简单的问题,但我无法弄清楚我是如何做到这一点的。我想以某种方式循环for循环中的项目。代码所做的是将图片垂直放置在彼此之上。此代码适用于3张图片(值= 3),但如果我想要更少或更多图片,我必须继续添加/删除新行,即Pixel pixel7等。

我需要一种方法来根据值中的数字来循环它。我不是在找你为我编写代码,只是让我知道如何做到这一点。感谢您的时间和帮助!

1 个答案:

答案 0 :(得分:0)

您必须修改方法,以便为每个像素循环value次:

public static Picture modifyPicture (Picture p, int value)
 {
  // get width and height of the picture
  int width = p.getWidth();
  int height = p.getHeight();
  System.out.println ("Picture has width of " + width + 
                      " and height of " + height);    
  Picture p2 = new Picture (width, height*value);

  for  (int x = 0 ; x < width ;  ++x )
  {
    for (int y = 0 ; y < height ; ++y )
    {
     Pixel pixel1 = p.getPixel (x,y);
     Color c1 = pixel1.getColor();

     for (int j=1; j < value; j++) {
          Pixel pixel = p2.getPixel (x, y + j * height);
          pixel.setColor( c1 );
     }
   }
 }
 return p2; 
}  // end of method