0

我想问你是否可以将我的代码更改/分解为 2-3 个类,添加构造函数(如果可能不为空)和/或添加更多方法。如果需要程序可以有更多的功能。

 public class Testing {


            public static void main(String args[]) throws Exception {
                Scanner input = new Scanner(System.in);
                System.out.println("Select word from list:");
                System.out.println();

                try {
                    FileReader fr = new FileReader("src/lt/kvk/i3_2/test/List.txt"); // this is list of words, everything all right here
                    BufferedReader br = new BufferedReader(fr);
                    String s;
                    while((s = br.readLine()) != null) {
                        System.out.println(s);
                    }
                    fr.close();
                    String stilius = input.nextLine();   // eneter word which I want to count in File.txt
                    BufferedReader bf = new BufferedReader(new FileReader("src/lt/kvk/i3_2/test/File.txt")); // from this file I need to count word which I entered before

                    int counter = 0;                
                    String line;

                    System.out.println("Looking for information");
                    ArrayList<String> resultList = new ArrayList<String>();
                    String name = null;
            while (( line = bf.readLine()) != null){
                    if (line.trim().length() == 0) name = null;
                    else if (name == null) name = line;
                    int indexfound = line.indexOf(stilius);
                          if (indexfound > -1) {
                   counter++;
                   resultList.add(name);
   }
                    }
                    if (counter > 0) {
                        System.out.println("Word are repeated "+ counter + "times");}
                        else {
                        System.out.println("Error...");
                    }
                    bf.close(); 

                }
                catch (IOException e) {
                    System.out.println("Error:" + e.toString());
                    }
                }
            }

从 file.txt 计算单词(通过键盘输入)并选择谁重复了这个单词,例如:如果我输入单词:One它显示:

Word One repeated 3 times by John, Elisa, Albert

file.txt 看起来像:

John //first line - name
One
Three
Four

Peter //first line - name
Two
Three

Elisa //first line - name
One
Three

Albert //first line - name
One
Three
Four

Nicole //first line - name
Two
Four

我真的不知道是否可以将此代码分解为 2-3 个类。如果有人可以帮助我,非常感谢。

4

1 回答 1

0

我将从定义两个类开始:

  • 字文件
  • WordFileEntry

一个 WordFile-object 应该包含一个 WordFileEntry-objects 的列表。WordFileEntry 由字符串名称和 List<String> 单词组成。

重复计数可以由 WordFile 对象本身完成。读取文件的逻辑可以写在 WordFile 类或单独的类中。

于 2012-11-12T12:43:01.663 回答