尝试让我的输出如下所示:UserInputViaCommand: match1, match2
但它显示:UserInputViaCommand: match1, UserInputViaCommand: match2
我知道这是因为第二个 for 循环位于第一个 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 + ", ");
}
另一种可能性是循环的顺序可以颠倒,您首先通读用户参数,然后在外循环中设置output.append(ags[j] + ":");
,然后寻找文件的开头来读取第二个参数(我将使用 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();
}
人们可以承认寻找文件开头的效率低下,但如果它不是瓶颈,那么这是一个可行的选择。
关于java - 封装的 For 循环导致问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21167651/