繁体   English   中英

装入For循环导致问题

[英]Encased For loops causing issues

尝试使我的输出看起来像以下内容: UserInputViaCommand: match1, match2

但它显示: UserInputViaCommand: match1, UserInputViaCommand: match2

我知道这是由于第二个for循环位于第一个循环中,但是我不确定是否要获得所需的输出。

我的程序像这样从命令行运行: java program name1 name2 < names.txt

我读取了文件并对其中的名称进行了规范化,然后读取用户输入并执行相同的操作,如果它们匹配,则将它们打印出来。

try {
    InputReader = new BufferedReader(new InputStreamReader(System.in));
    while ((nameFile = InputReader.readLine()) != null) {
        //Normalising the input to find matches
        nameFromFile = normalize(nameFile);
        //Looping through each argument
        for (int j = 0; j < ags.length; j++) {
            // Appending text to the string builder
            //Output.append(ags[j] + ":" + " ");
            //Normalising the input to find matches
            String result = normalize(ags[j]);
            if (nameFromFile.equalsIgnoreCase(result)) {
                Output.append(ags[j] + ":" + " " + nameFile + ", ");
                //Output.append(ags[j] + ":" + " ");
                //Output.append(nameFile + ", ");
            }
        }
    }
    System.out.println(Output);
}
catch (IOException e) {
    System.out.println(e.getMessage());
}

一种简单的方法是使用ags[j] + ":"检查是否已经出现在缓冲区中,因为通过命令行的用户输入是不同的

因此,您的内部if条件将类似于:

if (nameFromFile.equalsIgnoreCase(result)) {
    if (!output.toString().contains(ags[j] + ":"))
        output.append(ags[j] + ":");
    output.append(" " + nameFile + ", ");

}

另一种可能是循环的顺序可以颠倒,您首先要通过读取用户args来设置output.append(ags[j] + ":"); 在外循环中,然后寻找文件的开头以读取它作为第二个arg(我将使用RandomAccessFile轻松寻找文件的开头):

就像是:

try {

            RandomAccessFile raf = new RandomAccessFile(new File(
                    "C://users//XX//desktop//names.txt"),
                    "rw");

            for (int j = 0; j < args.length; j++) {
                output.append(args[j] + ":");
                while ((nameFile = raf.readLine()) != null) {

                    if (args[j].equalsIgnoreCase(nameFile)) {
                        output.append(" " + nameFile + ", ");

                    }

                }
                raf.seek(0);
            }
            System.out.println(output + "\r\n");

        } catch (IOException e) {
            e.printStackTrace();
        }

可以争辩到寻找文件开头的效率低下,但是如果它不是瓶颈,那么这是一个可行的选择。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM