Trying to get my output to look like the following: UserInputViaCommand: match1, match2
But it is displaying: UserInputViaCommand: match1, UserInputViaCommand: match2
I know this is due to the second for loop being inside the first one, but I am unsure about to to go about getting my desired output.
My program is run from the command line like so: java program name1 name2 < names.txt
I read the file and normalize names within it and then read the user input and do the same and if they match print them out.
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());
}
A simple way of doing it would be using a check for ags[j] + ":"
already appearing in your buffer, given that user input through command line would be distinct
So your inner if condition would be something like:
if (nameFromFile.equalsIgnoreCase(result)) {
if (!output.toString().contains(ags[j] + ":"))
output.append(ags[j] + ":");
output.append(" " + nameFile + ", ");
}
Another possibility can be loops' order can be reversed, you read through the user args first setting the output.append(ags[j] + ":");
in the outer loop and then seeking to the start of the file to read through it for the second arg (I would use RandomAccessFile
to easily seek to the start of the file):
Something like:
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();
}
One can contend the inefficiency of seeking to the start of the file but if it is not a bottleneck then is a feasible option.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.