为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

蓝山帝景 2024-01-05 15:12:37
我正在尝试读取并打印每个字符旁边有空格(txt 文件中的第 3 行之后)。如何在每个字符后添加空格?我的输入文件 txt 如下所示(忽略前 3 行):6111211211111TT.............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 + ' '); 但没有成功。有什么建议吗?
查看完整描述

3 回答

?
浮云间

TA贡献1829条经验 获得超4个赞

您可以使用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();

    }

}


查看完整回答
反对 回复 2024-01-05
?
守着一只汪

TA贡献1872条经验 获得超3个赞

您可以按如下方式进行操作:


import java.io.File;

import java.io.FileNotFoundException;

import java.nio.charset.StandardCharsets;

import java.util.Scanner;

public class Main {

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

        File file=new File("demo.txt");

        Scanner sc = new Scanner(file,StandardCharsets.UTF_8.name());


        //Ignore first three lines

        int count=0;

        while(count<3){

            sc.nextLine();

            count++;

        }


        //Add space after each character in the remaining lines

        while(sc.hasNext()) {

            String line=sc.nextLine();

            char []chars=line.toCharArray();

            for(char c:chars)

                System.out.printf("%c ",c);

            System.out.println();

        }

    }

}

输出:


T . T . . . 

. . . . . . 

. . . . T . 

. . . . T . 

T T T . . . 

. . . . . . 


查看完整回答
反对 回复 2024-01-05
?
青春有我

TA贡献1784条经验 获得超8个赞

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



查看完整回答
反对 回复 2024-01-05
  • 3 回答
  • 0 关注
  • 54 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信