布尔故障(代表我)

时间:2012-03-14 08:21:26

标签: java

我几天前在这里发了一个关于这个文件的帖子,它得到了一些好的答案/想法,我还没有实施,因为我一直在工作和喝酒,没有时间到处走走到目前为止(笑)。无论如何,我重新发布的原因是因为我提出了这个问题。我遇到的问题是我的while(_active)循环,我已经将我的Main类和我的commandCreate类包装成一个简单的文件退出,只需将boolean更改为false即可。但是,在我的commandCreate类中,boolean设置为false,虽然它是false,但是我无法进入Create部分,因为它不允许我这样做,它只是继续回到Main,在哪里 - 好像我将布尔值更改为true,它会自动直接转到Create部分,完全跳过Main类,即使我启动到Main类。如果有人能够帮助我,我的Main和commandCreate类都在下面。

不建议我将commandCreate更改为方法,并立即更改任何内容,我只想修复此问题

Main.java

import java.io.*;
import java.util.*;

public class Main extends API {
       private boolean _active = true;
     String _username = System.getProperty("user.name").toLowerCase();
     String _os = System.getProperty("os.name").trim().toLowerCase();

     CommandCreate create = new CommandCreate();

    public Main() {
         try {
            while(_active) {
                BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                print(username() + "@" + os() + ":~$ ");
                String command = br.readLine();
                    if(command.equalsIgnoreCase("create")) {
                        new CommandCreate();
                    /*} else if(command.equals("compile")) {
                        new CommandCompile();*/
                    } else if(command.equalsIgnoreCase("help")) {
                        println("Commands");
                        println(" create              - Creates .java files, does not compile.");
                        //println(" compile             - Creates .java files, compiles on creation.");
                        println(" exit                - Exits program");
                        println(" help                - Shows help documentation.");
                    } else if(command.equalsIgnoreCase("exit")) {
                        /*print("Are you sure you want to exit? (Y/N) ");
                        String exit = br.readLine();
                        if(exit.equalsIgnoreCase("y")) {
                        exit();*/
                        _active = false;
                        /*} else {
                        println("Cancelled!");
                        }*/
                    } else if(command.isEmpty()) {

                    } else {
                        println("\"" + command + "\" does not exist. Please review the \"help\" menu");
                    }
            }
        } catch(IOException ex) {
            ex.printStackTrace();
            }
   }

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

commandCreate.java

import java.util.*;
import java.io.*;

public class commandCreate {
    boolean _active = true;
   String _username = System.getProperty("user.name").toLowerCase();
   String _os = System.getProperty("os.name").trim().toLowerCase();
   String fileName, create, option;

    public commandCreate() {
        try {
         while(_active) {
            System.out.print(_username + "@" + _os + ":~/create$ ");
            Scanner kbd = new Scanner(System.in);
                String userLine = kbd.nextLine();

            if(java.util.regex.Pattern.matches(".*\\S\\s+\\S.*", userLine)) {
                    Scanner read = new Scanner(userLine);
                        option = read.next();
                        fileName = read.next();
            }

            FileWriter create = new FileWriter(new File("Created Files/" + fileName + ".java"));

            if(userLine.equals(option + " " + fileName)) {
                if(option.equals("-a")) {
                    // Option = -a, creates standard file with main class.
                    create.write("public class " + fileName + " {\n");
                    create.write("  public static void main(String[] args) {\n");
                    create.write("      System.out.println(\"Welcome to your new program!\");\n");
                    create.write("  }\n");
                    create.write("}");
                } else if(option.equals("-c")) {
                    // Option = -c , creates standard file with overloaded constructor & main class.
                    create.write("public class " + fileName + " {\n");
                    create.write("  public " + fileName + "() {\n");
                    create.write("      System.out.println(\"Welcome to your new program!\");\n");
                    create.write("  }\n");
                    create.write("\n");
                    create.write("  public static void main(String[] args) {\n");
                    create.write("      new " + fileName + "();\n");
                    create.write("  }\n");
                    create.write("}");
                } else if(option.equals("-j")) {
                    // Option = -j, creates GUI within constructor w/ single JLabel.
                    create.write("import javax.swing.*;\n");
                    create.write("import java.awt.*;\n");
                    create.write("import java.awt.event.*;\n");
                    create.write("\n");
                    create.write("public class " + fileName + " extends JFrame {\n");
                    create.write("  private static final int HEIGHT = 50;\n");
                    create.write("  private static final int WIDTH = 400;\n");
                    create.write("\n");
                    create.write("  private JLabel welcomeJ;\n");
                    create.write("\n");
                    create.write("  public " + fileName + "() {\n");
                    create.write("    super(\"Welcome to your program - " + fileName + "\");\n");
                    create.write("      Container pane = getContentPane();\n");
                    create.write("    setLayout(new FlowLayout());\n");
                    create.write("\n");
                    create.write("      welcomeJ = new JLabel(\"Welcome To Your Program!\", SwingConstants.CENTER);\n");
                    create.write("\n");
                    create.write("      pane.add(welcomeJ);\n");
                    create.write("\n");
                    create.write("     setSize(WIDTH, HEIGHT);\n");
                    create.write("     setVisible(true);\n");
                    create.write("     setResizable(false);\n");
                    create.write("     setDefaultCloseOperation(EXIT_ON_CLOSE);\n");
                    create.write("  }\n");
                    create.write("\n");
                    create.write("  public static void main(String[] args) {\n");
                    create.write("      new " + fileName + "();\n");
                    create.write("  }\n");
                    create.write("}");
                }
            } else if(userLine.equalsIgnoreCase("help")) {
                System.out.println("Commands");
                System.out.println("  Syntax: [-option] [filename]");
                System.out.println("      -a [filename]      [Program: main class]");
                System.out.println("      -c [filename]      [Program: overloaded constructor, main class]");
                System.out.println("      -j [filename]      [Program: GUI: overloaded constructor, main class]");
            } else if(userLine.equalsIgnoreCase("exit")) {
                System.exit(0);
            } else {
                System.out.println("Error in syntax. Please review the \"help\" menu");
            }
            create.close();
         }
        } catch(IOException e) {
            System.out.println("There was an error: " + e);
        } catch(InputMismatchException ex) {
            System.out.println("There was an error: " + ex);
        }
    }

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

2 个答案:

答案 0 :(得分:2)

问题是您在类构造函数中执行所有操作。构造函数体只应包含创建类实例所必需的代码。永远不要将应用程序逻辑放在构造函数中。

Main中,您初始化字段create时会产生{side}效果,只要您创建CommandCreate实例,就会执行Main代码。这发生在之前 Main类构造函数中的代码被执行。

通过清除构造函数并将代码移动到CreateCommandMain上的方法来修复它。

答案 1 :(得分:0)

我不确定我是否正确理解了你的问题,但有些事情对我来说真的很奇怪,而且我也觉得你在那里有一种误解。

首先,_activeMain中的commandCreate变量(顺便说一句,根据公约类名称应以大写字母开头)是完全独立的,你必须如果您希望它们相互依赖,请手动同步它们。

其次,你似乎在两个地方处理一些命令,例如MaincommandCreate都处理"exit"命令。根据我的假设你想要实现,只有Main(或更好的专业CommandProcessor)应该处理全局命令。因此"exit"在执行commandCreate时应该具有不同的含义(它不应该停止应用程序本身),或者您可能希望引入另一个命令以指示应该完成"create"命令。

但是你处理这些命令时Main中的循环应该检查它们的状态,并且是唯一一个停止应用程序并且可能先进行清理的命令。如果将"exit"命令保留在commandCreate内,它可能只是以适当的方式通知命令处理器(Main)(侦听器回调,设置一些标志等)。 / p>

修改

另外一个观察:你没有创建任何Main的实例,因此构造函数中的循环(正如@Andreas_D已经指出的那样已经很糟糕)永远不会被执行。