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