分解更多类并添加构造函数

时间:2012-11-12 11:49:17

标签: java file class methods constructor

我想问你是否可以将我的代码更改/分解为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个类。如果有人可以帮助我,非常感谢你。

1 个答案:

答案 0 :(得分:0)

我首先要定义两个类:

  • WordFile
  • WordFileEntry

WordFile对象应包含WordFileEntry对象列表。 WordFileEntry由String name和List&lt; String&gt;组成。词语的

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