【发布时间】:2012-11-12 11:49:17
【问题描述】:
我想问你是否可以将我的代码更改/分解为 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) 确定可以独立工作并提供特定功能的代码部分。 2) 对其进行修改,使其以灵活且易于维护的方式发挥作用。 3) 完成。 (
FileReader fr ...到fr.close();- 可以做成public static String readFile(File file){...}方法 - 然后你可以把它放到public static class FileUtils{...}类中,例如。) -
我认为你最好在 codereview 上问这个问题
-
一切皆有可能,你毕竟是程序员,不是吗?
标签: java file class methods constructor