java关闭扫描仪导致异常?

时间:2020-10-16 23:13:14

标签: java javafx java.util.scanner

我正在制作一个程序,将指令从文本文件转换为图形。该文件包含命令和参数,例如“ CIRCLE 100 200 15”。一旦扫描仪碰到说“结束”的行,我就需要关闭扫描仪,停止读取文件并停止绘制。但是当我在END开关的情况下使用'obj.close()'时,我得到了InvocationTargetException,RuntimeException和IllegalStateException。我试图查找解决方案,但找不到适合我的情况的解决方案。我尝试使扫描仪变为静态,这会导致错误,提示“此处不允许使用修饰符静态”,使其变为try语句,将其移至try语句之外,但没有任何效果。这是代码:

alert.message

这是错误:

public class Graphic extends Application {
    /**
     * The start method. Required by Application
     *
     * @param stage
     */
    public void start(Stage stage) {
        double fwidth = 0;
        double fheight = 0;
        ...

        Group root = new Group();  //creates group for all shapes to go in
        try {
            Scanner obj = new Scanner(new File("star.txt"));  //reads text file
            while(obj.hasNextLine()){
                String[] strArray = obj.nextLine().split(" ");  //splits all commands to new line
                switch(strArray[0]){
                    case "SIZE":                                      //sets size of window
                        ...
                    case "LINE":                                      //creates each line
                        ...
                    case "CIRCLE":                                    //creates each circle
                        ...
                    case "RECTANGLE":                                 //creates each rectangle
                        ...
                    case "TEXT":                                      //creates each string of text
                        ...
                    case "//":                                        //ignores comments
                        ...
                    case "END":                                       //stops reading file
                        obj.close();
                        break;
                }
            }

            Scene scene = new Scene(root, fwidth, fheight, Color.BLACK);
            stage.setTitle("poop");
            stage.setScene(scene);
            stage.show();
        }
        catch (FileNotFoundException fileNotFoundException) {
            fileNotFoundException.printStackTrace();
        }
        }

        /**
         * The main method
         * @param args
         */

        public static void main(String[] args) {
            launch(args);
        }
    }

idk,如果它是一个简单的修复程序,而我只是想念它或什么,但是如果有人可以提供帮助,将不胜感激。

1 个答案:

答案 0 :(得分:3)

将循环放在try-with-resources块中,然后它将自动关闭扫描器,因为Scanner实现了Closeable。

try (Scanner obj = new Scanner(new File("star.txt"))) {
    //Place your whole while loop here
}

您会脱离开关/案例,因此应该在try内的循环上方创建一个布尔值,然后在“ END”上将其设置为true。 然后在循环中检查变量的值,如果它是true,则像这样跳出循环:

在while循环上方:

boolean shouldBreak = false;

结束情况:

case "END":
    shouldBreak = true;
    break;

然后在循环的结尾(内部)

if(shouldBreak) break;
相关问题