2014-12-03 38 views
0

有人可以告诉我如何从下面的代码创建其他类吗? 我的老师不仅仅需要一个班级来完成这个任务,但是我在一个班级中完成了所有任务,所以如果可能的话,我需要帮助将其划分为多个班级。这是在Netbeans。创建多个类

package stringfinder; 

/** 
* 
* @author Christopher, Martin, Rasmus 
* @version 1.00 
*/ 
import java.io.BufferedReader; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.io.IOException; 
import java.util.Scanner; 


public class StringFinder { 

    public void run() 
    { 
     int count = 0, countBuffer=0; 
     //Enter the filepath to your desired text file. 
     String filePath = "C:\\Users\\Christopher\\Dropbox\\Skole\\WordDistance\\words.txt"; 
     BufferedReader br; 
     String line = ""; 
     String inputSearch = ""; 

     Scanner input = new Scanner(System.in); 

     try { 
     /** 
     * The first line welcomes the user to the application 
     * the second one tells the user to enter a keyword 
     * @param inputSearch is the keyword the user enters in the console. 
     */ 
      System.out.println("Welcome to Word Distance App"); 
      System.out.print("Enter a keyword: "); 

      inputSearch = input.nextLine(); 

      inputSearch = inputSearch.toLowerCase(); 

      br = new BufferedReader(new FileReader(filePath)); 
      try { 
       while((line = br.readLine()) != null) 
       { 
        String[] words = line.split(" "); 

        for (String word : words) { 
         if (word.equals(inputSearch)) { 
          count++; 
          countBuffer++; 
          } 
        } 

        if(countBuffer > 0) 
        { 
         countBuffer = 0; 
        } 

       } 
       br.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } 

     /** 
     * The last two lines shows the how much the entered keyword differs from the actual word in words.txt 
     * @param count how many words were found 
     * @param inputSearch the previously entered keyword 
     */ 
     System.out.println("Distance 0. "+"("+count+" word)"); 
     System.out.println(inputSearch); 
    } 
} 

回答

0

它不仅仅是一个类,而且是一个单一的功能。写错综复杂的功能并不是很好的风格,如果不是不可能的话,重复使用也很难。这也不是面向对象的。

不知道你的代码的目的/上下文是什么,我可以识别3可能的分割点:

  • 逻辑与定位和打开文件的交易。它应该接受文件名作为参数并返回流。
  • 处理搜索字符串的逻辑。它应该将开放流和字符串搜索为参数并返回现在的内容count
  • 将这两部分组合在一起的控制器逻辑。它应该获取文件名和字符串以搜索用户输入或 - 更好的命令行参数,调用其他两个函数,然后打印输出。

封装所述序列检索逻辑进入StringFinder类和其他部分移动到Main类可能是一个合理的设计。

根据经验对好设计的一个非常重要的原则,从来没有想过什么要计算(参数,用户交互,...)混合与细节定义东西是如何计算(算法)的逻辑。

-1

在相同的文件夹中创建第二文件SecondClass.java作为StringFinder.java

在其添加:

package stringfinder; 


public class SecondClass{ 

// some code 
    public void someMethod(){ 
    } 

} 

然后内StringFinder.run()

SecondClass obj = new SecondClass(); 
obj.someMethod(); 
0

请注意,我对Java一无所知,因为我只能将它与Python进行比较,但OOP是OOP,并且通过阅读代码,您似乎错过了Java旨在让您做的OOP部分。

如果是我:

我会尝试并打开文件与字符串自己变成文件实例/从自己的类对象

public class FileClass{ 

insertYourStringFileCodeHere 


}