2

How can I use a batch file to work as a Java console that accepts input? I made a test application with a couple commands, and I run the jar file using this line in a batch file:

java -cp console.jar test.Main

When I attempt to type something in the batch window, it closes. What would be the correct approach?

Here is my main method. I use a Scanner to get the user input.

public static void main(String[] args) {
    scanner = new Scanner(System.in);

    String line = scanner.nextLine();

    if (line.startsWith("--")) {
        String[] command = line.split("--");
        new Command(command[1]);
    }
}

Thanks in advance.

1
  • If that is the real program: of course it closes. It creates a new Command instance and then does nothing. So the program terminates. What else did you expect? Commented Nov 22, 2013 at 14:09

1 Answer 1

1

You can write pause at the end of your batch file so that it won't close automatically on you. Then you can see the output from your program.

The terminal will close when it's done the job that it was assigned to do.

After taking a closer look at your code, it looks line you want to continually accept input and run a command based on that. In that case you want:

String line = scanner.nextLine();

while(line != null && !line.equals(""))
{
    if (line.startsWith("--")) {
        String[] command = line.split("--");
        new Command(command[1]);
    }
    line = scanner.nextLine();
}
Sign up to request clarification or add additional context in comments.

1 Comment

I have already tried that, but the problem wasn't an automatic close, it was a close whenever I try to type something, seems like it's the same thing when I try to run it in Eclipse.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.