我有一个应该上学的项目,绘制形状并使它们移动。该程序(我认为是困难的部分)工作正常,但老师将使用文本文件测试它。我很难打破她将要使用的命令。我正在使用缓冲区读取器来读取文件,然后我循环遍历令牌,但这就是我感到困惑的地方。我如何将令牌分解为字符串和整数并触发正确的方法?任何建设性的指导都将不胜感激。
这是我读取文件的代码
static void getTokens() throws Exception {
Scanner input = new Scanner(System.in);
System.out.print("Please enter the file name ---> ");
fileName = input.next();
FileReader fr = new FileReader(fileName);
BufferedReader inFile = new BufferedReader(fr);
String element = inFile.readLine();
// tokenize string with " " as the delimiter
StringTokenizer tokenizer = new StringTokenizer(element, " ");
// loop through tokens
while (tokenizer.hasMoreTokens()) {
txtAnalysis(tokenizer.nextToken());
}
//close file
inFile.close();
}
以下是教师将使用的文字示例。
start picture A
circle 50 100 20
coloredcircle 0 100 20 green
end picture
draw picture A blue 10 10
dance picture A 30 30
erase
start picture B
rectangle 0 100 20 40
rectangle 100 100 40 20
rectangle 200 100 40 20
Sshape 55 55 55 55 55 yellow Elf
Sshape 55 25 35 45 65 red Ogre
end picture
draw picture B yellow 10 10
erase
draw picture A blue 10 10
答案 0 :(得分:2)
这样的事情?
public void txtAnalysis(String line){
if(line.startsWith("start picture")){
String label = line.split(" ")[2];
currentPicture = new Picture(label);
}
if(line.startsWith("end picture")){
save(currentPicture);//or pictures.put(currentPicture.getLabel(), currentPicture);
currentPicture = null;
}
if(line.startsWith("circle")){
String[] parts = line.split(" ");
currentPicture.addShape(new Cirlce(Integer.parseInt(parts[1]), Integer.parseInt(parts[2]), Integer.parseInt(parts[3])));
}
if(line.startsWith("draw picture")){
String[] parts = line.split(" ");
Picture pic = pictures.get(parts[2]);
pic.draw(parts[3], Integer.parseInt(parts[4]), Integer.parseInt(parts[5]));
}
...
}
你正在寻找这样的东西吗?
答案 1 :(得分:0)
我将使用某种策略或工厂模式。
// loop through tokens
while (tokenizer.hasMoreTokens()) {
DrawerFactory factory =
AbstractProgramFactory.getFactory(tokenizer.nextToken());
factory.process(tokenizer);
}
然后您的AbstractProgramFactory.getFactory将具有if / else行为,并将返回一个知道如何执行任何命令的实现。
interface DrawerFactory{
void process(final Tokenizer tokenizer);
}