1

ファイルからコンテンツを読み取り、画面に出力するプログラムがあります。しかし、プログラムは 1 行おきに出力します。つまり、1 行おきにスキップします。パッケージ入出力;

import java.io.*;

public class CharacterFileReaderAndFileWriter{

    private BufferedReader br = null;

    private PrintWriter pw = new PrintWriter(System.out, true);


    /* Read from file and print to console */
    public void readFromFile() throws IOException{

        try{
            br = new BufferedReader(new FileReader("E:\\Programming\\Class files\\practice\\src\\InputOutput\\test.txt"));
        }
        catch(FileNotFoundException ex){
            ex.printStackTrace();
        }

        String s = null;
        do{
            s = br.readLine();
            pw.println(s);
        }
        while((s = br.readLine())!=null);

        br.close();
    }

    /* Main method */
    public static void main(String[] args) throws IOException{

        CharacterFileReaderAndFileWriter cfr = new CharacterFileReaderAndFileWriter();

        cfr.readFromFile();
    }

}
4

7 に答える 7

6

なぜあなたは二度やっているs=br.readline()のですか..あなたはこのようにそれをすることができます.

String s = null;
 while((s = br.readLine())!=null)
{
   pw.println(s);
}

readline()呼び出すたびに行を読み取り、次の行に進みます。したがって、2回呼び出すと、明らかに行をスキップしています。このコードを使用すると、機能します。

于 2012-04-22T02:53:36.117 に答える
1

あなたのループは間違っています:

String s = null;
do{
    s = br.readLine();
    pw.println(s);
}
while((s = br.readLine())!=null);

次のようにする必要があります。

String s = null;
while((s = br.readLine())!=null) {
    pw.println(s);
};
于 2012-04-22T02:53:56.367 に答える
1

do/whileループを逆にして、 readline2 回呼び出して他のすべての結果を破棄しないようにします。

String s = null;
while((s = br.readLine())!=null) {
    pw.println(s);
}
于 2012-04-22T02:54:11.187 に答える
0

doループの最初の行を削除します。readLine() を 2 回呼び出しています。

すなわち:

String s = null;
while((s = br.readLine())!=null) {
    pw.println(s);
}
于 2012-04-22T02:52:24.607 に答える
0

br.readLine() を 2 回使用しています。

String s = null;
    do{
        s = br.readLine();  //here it read first line 
        pw.println(s);      //here it prints first line    
    }
    while((s = br.readLine())!=null); //here s read second line
                                      //note that it is not printing that line

String s = null;
    do{
        s = br.readLine();  //this time it read third line
        pw.println(s);      //now it prints third line
    }
    while((s = br.readLine())!=null);   // this time it reads fourth line 

したがって、このプロセスは続き、プログラムは行を次々と出力します。

于 2013-07-03T04:40:57.997 に答える
0

do-while を使用する場合は、do-while ループを変更する必要があります。次に、次のようにコーディングしてください。

String s = null;
do{        
    pw.println(s);
}
while((s = br.readLine())!=null);

br.close();
于 2012-04-22T02:56:11.670 に答える
0

変更:

  for(String s; (s = br.readLine()) != null;) {
        pw.println(s);
  }
于 2012-04-22T03:01:00.627 に答える