猿问

如何从文件中读取多个字符,将字符乘以网格并打印回新文件

我正在尝试从文件中读取多个字符,使每个字符相乘,以便当我将其打印到新文件时,它们以网格状格式显示。


    int num = 4;

    String fileStr = "";


    scnrIn.useDelimiter("zzzzzzzzz");


    while(scnrIn.hasNextLine()) {

        fileStr = scnrIn.nextLine();


        char[] charArray = fileStr.toCharArray();


        for(int i = 0; i < charArray.length; ++i) {

            for(int j = 0; j < Math.sqrt(num); ++j) {

                writer.write(charArray[i]);

                for(int k = 1; k < Math.sqrt(num); ++k) {

                    writer.write(charArray[i]);

            }

                writer.newLine();

                writer.flush();

        }

        }

    }



}

}


如果我的 txt 文件包含字符 @#$,而我的多像素为 4,我希望打印新的 txt 文件:


@@##$$

@@##$$

但相反,我得到:


@@

@@

##

##

$$

$$

我觉得这个问题与writer.newLine()有关。但是如果我把它拿走或注释掉,那么它就不会在网格中打印出来。我不确定如何解决在网格中打印新行的需求。


慕慕森
浏览 112回答 1
1回答

慕桂英546537

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

相关分类

Java
我要回答