1 回答
TA贡献1848条经验 获得超10个赞
您的问题与 for 循环的嵌套有关。如果按照代码执行的操作,则会在网格中写出一个当前字符,然后转到 .icharArray
相反,您应该做的是逐行并为每个字符打印出当前字符的列数,然后再转到新行。这主要需要切换两个最外部的 for 循环,然后修复调用 write 的频率。
以下是按预期工作的代码:
int num = 4;
int cols = (int) Math.sqrt(num); //easier to read the code when stored in a variable
int rows = cols;
String fileStr = "";
scnrIn.useDelimiter("zzzzzzzzz");
while(scnrIn.hasNextLine()) {
fileStr = scnrIn.nextLine();
char[] charArray = fileStr.toCharArray();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < charArray.length; j++) {
char curChar = charArray[j]; //this is the current character we want to write out for the number of columns times
for (int k = 0; k < cols; k++) {
writer.write(curChar);
}
}
writer.newLine(); //create a new line after every row
}
writer.flush(); //better to only flush output when fully done
}
添加回答
举报