0

我有一个学校的项目要绘制形状并让它们移动。该程序(我认为是困难的部分)运行良好,但老师将使用文本文件对其进行测试。我很难打破她将使用的命令。我正在使用 bufferreader 读取文件,然后循环遍历令牌,但这就是我感到困惑的地方。我将如何将令牌分解为字符串和整数并触发正确的方法?任何建设性的指导将不胜感激。

这是我读取文件的代码

   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
4

2 回答 2

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]));
    }
    ...
}

你在找这样的东西吗?

于 2013-10-10T14:47:27.130 回答
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);
}
于 2013-10-10T14:27:07.940 回答