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 回答