2014-01-16 31 views
1

試圖讓我的輸出看起來像下面的循環: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()); 
} 
+1

這是一個有趣的for循環。你爲什麼不使用'while'循環?你基本上已經把'for'變成了'while'。 – crush

+0

@crush我做了瘋狂的變化,我認爲這是一個階段的while循環。我會改變它,看看我是否可以玩它。 :)更改爲while循環:) –

+1

您的示例輸出似乎不符合您的代碼。看起來輸出應該更類似於:'Name1:name1,name2:name2'。所以無論你在此期間改變了一些東西,還是你遺漏的代碼都是重要的一部分。 –

回答

0

這樣做將使用的支票ags[j] + ":"在你的緩衝區已經出現,因爲通過命令行用戶輸入將不同

所以,你的內心,如果條件會是這樣的一個簡單的方法:

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(); 
     } 

一個可以抗衡定位到文件開始的低效率,但如果它不是一個瓶頸然後是一個可行的選擇。

+1

非常感謝。 :)第一個例子迷人:) –