猿问

如何读取并打印每个字符(旁边有空格)

我正在尝试读取并打印每个字符旁边有空格(txt 文件中的第 3 行之后)。如何在每个字符后添加空格?

我的输入文件 txt 如下所示(忽略前 3 行):

6
111211
211111
TT...
......
....T。
....T。
TT
…………

我要打印的是:
T。T。。。
。。。。。。
。。。。T。
。。。。T。
TT。。。
。。。。。。

public static void main(String[] args) throws IOException {


    int size; // using it for first line

    int rows; // using it for second line

    int cols; // using it for third line

    // pass the path to the file as a parameter

    FileReader fr =

            new FileReader("input1.txt");


    int i;

    while ((i=fr.read()) != -1) {

        System.out.print((char) i);

    }

}

我正在尝试获取例外的输出,但我从文件中获取了相同的行。我尝试过使用 System.out.print((char) i + " "); 或 System.out.print((char) i + ' '); 但没有成功。有什么建议吗?


蓝山帝景
浏览 107回答 3
3回答

浮云间

您可以使用BufferedReader.public static void main(String[] args) throws IOException {    int size; // using it for first line    int rows; // using it for second line    int cols; // using it for third line    // pass the path to the file as a parameter    BufferedReader fr = new BufferedReader(        new FileReader("input1.txt")    );    // skipping 3 lines    fr.readLine();    fr.readLine();    fr.readLine();    String line = fr.readLine();    while (line != null) {        for (char c : line.toCharArray()) {            System.out.print(c + " ");        }        System.out.println();        line = fr.readLine();    }}

守着一只汪

您可以按如下方式进行操作:import java.io.File;import java.io.FileNotFoundException;import java.nio.charset.StandardCharsets;import java.util.Scanner;public class Main {&nbsp; &nbsp; public static void main(String[] args) throws FileNotFoundException {&nbsp; &nbsp; &nbsp; &nbsp; File file=new File("demo.txt");&nbsp; &nbsp; &nbsp; &nbsp; Scanner sc = new Scanner(file,StandardCharsets.UTF_8.name());&nbsp; &nbsp; &nbsp; &nbsp; //Ignore first three lines&nbsp; &nbsp; &nbsp; &nbsp; int count=0;&nbsp; &nbsp; &nbsp; &nbsp; while(count<3){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sc.nextLine();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; count++;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; //Add space after each character in the remaining lines&nbsp; &nbsp; &nbsp; &nbsp; while(sc.hasNext()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String line=sc.nextLine();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; char []chars=line.toCharArray();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(char c:chars)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.printf("%c ",c);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}输出:T . T . . .&nbsp;. . . . . .&nbsp;. . . . T .&nbsp;. . . . T .&nbsp;T T T . . .&nbsp;. . . . . .&nbsp;

青春有我

实际上,至少在 java 8 上,“System.out.print((char) i + " ");”&nbsp;应该可以正常工作。我现在刚刚尝试过并且对我来说效果很好。你使用的是哪个java版本?否则你可以按照@second的建议尝试BufferedReader。
随时随地看视频慕课网APP

相关分类

Java
我要回答