簡體   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