我正在用Java创建一个调度程序。我把所有内容放在一个类中,但现在我想把它拆分成单独的类。这是一个非常小的程序,所以可能没什么好处,但我想让它的概念正确。代码如下。
我在importTeams()方法的第二个类中遇到错误。我以为只要我导入了这个方法的包,就可以了。显然不是。有什么提示吗?
package fifa.scheduler.fileimport;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import fifa.scheduler.output.*;
public class FileRead2 {
private String rrTeam;
public List<String> importTeams() {
ArrayList<String> teamList = new ArrayList<String>();
BufferedReader br = null;
int linecount = 0;
String teamcounter;
try {
br = new BufferedReader(new FileReader("path"));
while (br.readLine() != null){
linecount ++;
}
br.close();
br = new BufferedReader(new FileReader("path"));
setRrTeam(br.readLine());
while ((teamcounter = br.readLine()) != null) {
teamList.add(teamcounter);
}
if (linecount % 2 != 0) {
teamList.add("byeteam");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return teamList;
}
public static void main(String args[]){
FileRead2 fr = new FileRead2();
fr.PrintTeams();
}
private void setRrTeam(String rrTeam) {
this.rrTeam = rrTeam;
}
private String getRrTeam() {
return rrTeam;
}
}
package fifa.scheduler.output;
import java.util.Collections;
import java.util.List;
import fifa.scheduler.fileimport.FileRead2;
public class SchedulerOutput {
public void PrintTeams(){
List<String> teamList = importTeams();
int tl = teamList.size();
int bh = 0;
int uh = (tl - 2);
for (int i = 0; i <=(teamList.size()-1); i++) {
System.out.println("Week " + (i+1) + " fixtures");
System.out.println(getRrTeam() + " vs " + teamList.get(tl -1));
while ((bh <= (tl / 2)) && (uh >= ((tl / 2)))) {
System.out.println(teamList.get(bh) + " vs " + teamList.get(uh));
bh++;
uh--;
}
Collections.rotate(teamList, 1);
tl = teamList.size();
bh = 0;
uh = (tl - 2);
}
}
}
答案 0 :(得分:2)
使用import
语句导入类时,仅导入类的接口。要调用成员方法,您需要该类的实例。
在您的情况下,您应该创建一个FileRead2
类型的对象来调用importTeams()
方法。
// Since FileRead2 has some member variable, you should also think about
// initializing it appropriately if it is needed by importTeams method.
FileRead2 fileRead2Obj = new FileRead2();
fileRead2Obj.importTeams();
类似地,要调用静态方法,您需要使用类名限定方法名称(尽管Java 5+也允许静态导入方法)。
如果importTeams()
是静态方法,那么在导入类后应该按如下方式调用它:
FileRead2.importTeams();