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