0
public static void main(String[] args) throws IOException{
if (args.length == 1)
{
    BufferedReader bf = new BufferedReader (new FileReader("fruit.txt"));
    int linecount = 0;
    String line;
    //run thur the txt file to check if input exist
    while (( line = bf.readLine()) != null)
    {
        linecount++;
        int indexfound = line.indexOf(args[0]);
        if (indexfound > -1) {
            System.out.println("fruit exist on line " + linecount);
            System.out.println("add another fruit");    
            System.exit(0);
        } else {
            BufferedWriter bw = new BufferedWriter(new FileWriter("fruit.txt", true));
            String fruit = "";
            fruit = args[0];
            bw.write("\r\n" + fruit);
            System.out.println(fruit+ "added"); 
        }
    }
    f.close();
    bw.close();
}

果物が既に存在するかどうかをチェックするテキスト ファイル fruit.txt を検索するプログラムを作成したいと考えています。

果物が存在する場合は、ユーザーに別の 1 を入力するように求める

それ以外の場合は、テキスト ファイルの次の行に追加します

これは私がこれまでに得たものです。しかし、なぜそれが私が望んでいたものではないのかわかりません。

私のテキストファイルでは、3つの果物で始まりました

apple
orange
pear

ベリーを入れた後

apple
orange
pear
berry
berry

メロンを入れたら

apple
orange
pear
berry
berry
melon
melon
melon
melon
4

1 に答える 1

2

最初の行で果物をチェックしているだけで、見つからない場合は追加を続けています。

最初にファイルを完全に読み取り、各行をチェックして、果物が含まれているかどうかを確認し、含まれていない場合は、その果物をダンプする必要があります。含まれている場合は拒否します。

したがって、その間に、他の部分を外側に移動する必要があります。果物が見つかったときに行うのではなくSystem.exit()、ブール変数を true に設定し、後でブール変数の値に基づいて、果物を追加するかどうかを決定できます。

boolean found = false;
while (( line = bf.readLine()) != null) {

    linecount++;
    int indexfound = line.indexOf(args[0]);
    if (indexfound > -1) {
        System.out.println("fruit exist on line " + linecount);
        System.out.println("add another fruit");   
        found = true;
        break;
    }
}

if (!found) {

    BufferedWriter bw = new BufferedWriter(new FileWriter("fruit.txt", true));
    String fruit = "";
    fruit = args[0];

    bw.write("\r\n" + fruit);
    System.out.println(fruit+ "added"); 

    bw.close();  // You need to close it here only. 
}

bf.close();                     
于 2012-10-24T07:00:56.510 に答える