亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何讀取并打印每個字符(旁邊有空格)

藍山帝景 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條經驗 獲得超4個贊

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


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 關注
  • 183 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號