[英]“Stretching” a 2D Array in Java
I need to "stretch" a 2D Array filled with chars of ' ', and '*'. 我需要“拉伸”填充有''和'*'字符的二维数组。 The stretching is based on a "Int Factor" passed in through the method.
拉伸基于通过该方法传递的“整数因子”。
Current Image looks like this: 当前图像如下所示:
*****
*
* *
***
* *
* *
*****
Need it to look like this: (Assuming its Factor 2) 需要它看起来像这样:(假设其因子2)
**********
**
** **
******
** **
** **
**********
I started to write the loop for it but I have no idea if I'm on the right track or not, really struggling with this one. 我开始为它编写循环,但是我不知道我是否走在正确的轨道上,真的为此挣扎。
EDIT: I've gotten the array col length to stretch, I need to get the image to stretch with it now. 编辑:我已经得到要延伸的数组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;
}
Image printed from this: 从此打印的图像:
****
**
**
****
Ok, some problems with your loop: 好的,您的循环存在一些问题:
for (int col = 0; col < pixels[0].length * factor; col--) for(int col = 0; col <pixel [0] .length * factor; col--)
Here, you should use pixels[row].length to get the correction column. 在这里,您应该使用pixels [row] .length来获取校正列。 Furthermore, it should be col++ instead of col--
此外,它应该是col ++而不是col--
If you only need to print the result, you don't actually need to stretch the array. 如果只需要打印结果,则实际上不需要拉伸数组。
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();
}
}
This prints the star/asterisk 'factor' times, and the spaces only as often as they occur in the original. 这将打印星号/星号的“因数”时间,以及空格,仅与它们在原件中出现的频率相同。
You're almost there. 你快到了。 All you have to do, is change the code so that you're copying
pixels[row][column]
to the new array factor
times 您所要做的就是更改代码,以便将
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.