[英]“Stretching” a 2D Array in Java
我需要“拉伸”填充有''和'*'字符的二维数组。 拉伸基于通过该方法传递的“整数因子”。
当前图像如下所示:
*****
*
* *
***
* *
* *
*****
需要它看起来像这样:(假设其因子2)
**********
**
** **
******
** **
** **
**********
我开始为它编写循环,但是我不知道我是否走在正确的轨道上,真的为此挣扎。
编辑:我已经得到要延伸的数组col长度,我现在需要使图像延伸。
public void stretch ( int factor )
{
factor = 2;
char[][] pixelStretch = new char[pixels.length][pixels[0].length * factor];
for (int row = 0; row < pixels.length; row++)
{
for (int col = 0; col < pixels[0].length; col+= factor) {
for(int i=0; i<factor; i++) {
pixelStretch[row][col+i] = pixels[row][col];
}
}
}
pixels = pixelStretch;
}
从此打印的图像:
****
**
**
****
好的,您的循环存在一些问题:
for(int col = 0; col <pixel [0] .length * factor; col--)
在这里,您应该使用pixels [row] .length来获取校正列。 此外,它应该是col ++而不是col--
如果只需要打印结果,则实际上不需要拉伸数组。
public void stretch ( int factor )
{
for (int row = 0; row < pixels.length; row++)
{
for (int col = 0; col < pixels[row].length; col++) {
char c = pixels[row][col];
if (c == ' ')
System.out.print(c);
else
for (int count = 0; count < factor; count++)
System.out.print(c);
}
System.out.println();
}
}
这将打印星号/星号的“因数”时间,以及空格,仅与它们在原件中出现的频率相同。
你快到了。 您所要做的就是更改代码,以便将pixels[row][column]
复制到新的数组factor
时间
// make sure factor is not 0 before you do this
for (int col = 0; col < pixels[0].length; col++) {
for(int i=0; i<factor; i++) {
pixelStretch[row][col*factor+i] = pixels[row][col];
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.