我注解了我的代码,以帮助您理解我的逻辑,我基本上收到一个边值,我必须画一个三角形使用x的视觉显示其周长(各方都是平等的)
因此,在创建将填充包含图形的矩阵的单个数组时,随着迭代的继续,一些赋值会丢失,只保留最后一次迭代的值,并用这些值填充整个矩阵,这使我失去了所有的前一行,组成一个漂亮的三角形绘图,我无法打印成一个txt文件(我可以通过在循环中打印来在控制台中打印它,因为它生成了对应于一条绘图线的每个数组,但这只是一个暂时的幻觉,因为我没有将矩阵和x保持在适当的位置)。
如果有人能帮我不失去这个价值,并且能把它储存起来,我会很高兴的。
注意:父类figura只提供一个名为lado的int。
public class Triangulo extends Figura {
char[] lineaI;
char[] lineaT;
char[][] matT;
public char[][] matDibujo(int lado) {
this.linea = new char[(lado+lado-1)]; //side int value to determine an eq. triangle base length
lineaI = new char[linea.length]; //multiple intermediate single arrays that fill triangle diagonally
lineaT = new char[linea.length]; //triangle base array
matT = new char[lado][linea.length]; // matrix containing {{},{},{},{}} n individual arrays representing a row in the drawing (top to bottom)
//Create triangle base line array
for (int i = 0; i < linea.length; i++) {
if (i == 0 ) {
linea[i] = 'X';
} else if (i%2 == 0) {
linea[i] = 'X';
} else {
linea[i] = ' ';
}
//Create triangle top point array
if (i == (lado-1)) {
lineaT[i] = 'X';
} else {
lineaT[i] = ' ';
}
}
//Fill matrix with first array (top axis)
matT[0] = lineaT;
//Fill matrix last array (triangle base)
matT[lado-1] = linea;
//System.out.println(matT[lado-1]);
//THIS IS THE LOOP NOT SAVING CORRESPONDING lineaI full single array to matT[j],
//instead it's replacing every matT[j] with the last value of lineaI.
//Create multiple arrays to fill n-sided triangle from top axis to base diagonally (parting from top axis)
for (int j = 1; j < (lado-1); j++) {
for (int i = 0; i < linea.length; i++) {
if (i == (lado-1-j) ) {
lineaI[i] = 'X';
} else if (i == (lado-1+j) ) {
lineaI[i] = 'X';
} else {
lineaI[i] = ' ';
}
}
matT[j] = lineaI;
}
//return the matrix so we can print it
return matT;
}
//Dibujar en txt
public void dibuja(char[][] matriz) {
for (int i = 0; i < matriz.length; i++) {
System.out.println(matriz[i]);
}
}
public static void main(String[] args) {
char[][] mat;
Triangulo t = new Triangulo();
mat = t.matDibujo(4);
t.dibuja(mat);
//This is the outcome, since we lost matT[1] and got it replaced by the last lineaI contents, which should
//only belong to matT[2]
/* X The outcome should be X
X X X X ---> this line is lost and
X X X X ----> replaced by this one
X X X X X X X X */
}
}
1条答案
按热度按时间u4dcyp6a1#
这里的问题是lineai数组值一旦计算出来,就将它赋给matt[j],然后再次用新值覆盖同一lineai引用,并为每个j值附加到matt。
这将导致值被覆盖,并显示所有间歇行的最终数组值。
要解决这个问题,只需在每个j值的迭代开始时,将lineai变量重新初始化为一个新数组。