taking a .txt file with bufferedReader , adding it to arraylist, and searching a word from it

StackOverflow https://stackoverflow.com/questions/22596022

  •  19-06-2023
  •  | 
  •  

문제

I have a dictionaryTXT.txt file, which stores word and their meaning, like "apple: a fruit","cat: an animal","bat: playing instrument" etc. Now I want to take the input from user and search a meaning. I am not being able to do the search. Can someone help?

public static void main (String[] args) throws IOException
  {
    List<String> lines = new ArrayList<String>();
    System.out.println("enter the word you want to search-");
          Scanner in= new Scanner(System.in);
    String input=in.nextLine();
    FileReader fileReader = new FileReader("dictionaryTXT.txt");
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    String line = null;
    while ((line = bufferedReader.readLine()) != null) {
        lines.add(line);
    }
        String [] words = lines.toArray(new String[lines.size()]);
        StringBuffer result = new StringBuffer();
        for (int j  = 0; j < words.length; j++)
       {
        result.append(words[j]);
       }
        String my = result.toString();
        int i = my.indexOf(":");
        String sub=my.substring(0,i);

        if(sub.equals(input))
        {

            System.out.println(my);

        }
        else
        {
            System.out.println("word not found");
        }
        bufferedReader.close();
       }

    }
도움이 되었습니까?

해결책

Use a Map<String, String>. And use Files.readAllLines():

final Map<String, String> entries = new HashMap<>();
final Path dict = Paths.get("dictionaryTXT.txt");

String[] array;

for (final String line: Files.readAllLines(dict, StandardCharsets.UTF_8)) {
    array = lines.split("\\s*:\\s*");
    entrues.put(array[0], array[1]);
}

Then to search for a word:

final String description = entries.get(input);

if (description == null)
    System.out.println("not found");
else
    System.out.println("definition: " + description);

Of course, if your dictionary is extra large, you'll want to use Files.newBufferedReader() instead and read line by line.

Also, the code above lacks basic error checking; exercise left to the reader

다른 팁

Please consider using a Map instead which is designed specifically for the purpose of lookup and retrieval.

Map<String, String> dictionary = new HashMap<String, String>();
while ((line = bufferedReader.readLine()) != null) {
    String[] lineArray = line.split(":");
    dictionary.put(lineArray[0].trim(), lineArray[1].trim());
}

Scanner in= new Scanner(System.in);
String input=in.nextLine();

if (dictionary.get(input) != null) {
  System.out.println(dictionary.get(input));
}
else {
  System.out.println("No definition found");
}

This is lookup compared to search which is much faster and efficient.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top