Guest User

Untitled

a guest
Jan 24th, 2018
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. import java.awt.HeadlessException;
  2. import java.io.File;
  3. import java.io.FileNotFoundException;
  4. import java.util.ArrayList;
  5. import java.util.Collection;
  6. import java.util.LinkedList;
  7. import java.util.Scanner;
  8. import javax.swing.JOptionPane;
  9. public class Dictionary {
  10. private String fileName;
  11. private Collection<String> words;
  12. private long elapsedTime;
  13. public Dictionary(String fileName) { this.fileName = fileName; }
  14. public void loadDictionary(Collection<String> words) throws FileNotFoundException{
  15. this.words = words;
  16. Scanner input = new Scanner(new File(fileName));
  17. long startTime = System.currentTimeMillis();
  18. while(input.hasNext()){
  19. String word = input.nextLine();
  20. words.add(word);
  21. }
  22. input.close();
  23. elapsedTime = System.currentTimeMillis() - startTime;
  24. System.out.printf("%s build time in %s collection: %.2f seconds \n",
  25. fileName, words.getClass().getName(), (double) elapsedTime / 1000.0);
  26. }
  27. public void display(){
  28. System.out.printf("Contents of %s, organized using %s: \n",
  29. fileName, words.getClass().getName());
  30. int wordCount = 0;
  31. for(String word : words){
  32. System.out.print(word + " ");
  33. if(++wordCount % 20 == 0){ // new line every 20 words
  34. System.out.println();
  35. }
  36. }
  37. System.out.printf("\nCollection: %s Elapse Time:%.2f Word Count: %d\n",
  38. words.getClass().getName(), (double)elapsedTime / 1000.0, wordCount);
  39. JOptionPane.showMessageDialog(null, "Make note of the results, then click OK to continue...");
  40. }
  41. public static void main(String[] args){
  42. try{
  43. String fileName = JOptionPane.showInputDialog("Dictionary file name: ");
  44. Dictionary test = new Dictionary(fileName);
  45. test.loadDictionary(new LinkedList<String>());
  46. test.display();
  47. test.loadDictionary(new ArrayList<String>());
  48. test.display();
  49. }
  50. catch(HeadlessException e){ // can be generated by JOptionPane.showInputDialog()
  51. e.printStackTrace();
  52. }
  53. catch(FileNotFoundException e){
  54. System.out.println("File not found");
  55. }
  56. }
  57. }
Add Comment
Please, Sign In to add comment