Hello, for task package com.codegym.task.task19.task1922 something is not making sense for me:
Display all of the file's lines that contain only 2 words in the words list.
A B A D // 3 words from words, rejected - what do you mean it has 3 words? It only has 2 which are A and B.
Does it count that A repeats itself? Because if it does, then this line:
D A A D // 2 words from words, accepted, display it
Would not qualify because it would have 4 words.
///////////////////////////////////////////////////////////////////////////////////////////
Searching for the right lines
Read a file name from the console.
Display all of the file's lines that contain only 2 words in the words list.
Close the streams.
Example:
words contains the words A, B, and C
Lines:
C B A D // 3 words from words, rejected
A B A D // 3 words from words, rejected
D A D // 1 word from words, rejected
D A B D // 2 words from words, accepted, display it
D A A D // 2 words from words, accepted, display it
package com.codegym.task.task19.task1922;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/*
Searching for the right lines
*/
public class Solution {
public static List<String> words = new ArrayList<>();
static {
words.add("file");
words.add("view");
words.add("In");
}
public static void main(String[] args) throws Exception {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String fileName = bf.readLine();
bf.close();
BufferedReader bf2 = new BufferedReader(new FileReader(fileName));
//Display all of the file's lines that contain only 2 words in the words list.
//compare each word from the line in the file against the words list
//have the counter increment. in the end, if the counter is 2, display the line,
//else move to the nextline
String[] fileWords;
int counter = 0;
while (bf2.ready()){
//read line from file
fileWords = bf2.readLine().split(" ");
for (String word : fileWords){
//for each word from file
for (String word2 : words){
//compare with word from array
if (word.equals(word2)) counter++;
break;
}
}
if (counter == 2) {
String word = fileWords[0];
for (int i = 1; i < fileWords.length; i++) word += " " + fileWords[i];
System.out.println(word);
}
counter = 0;
}
bf2.close();
}
}