Exit java program using ctrl+z? - java

I am creating a very simple program, asking the user to guess words. Guessing words works just with Scanner and System.out.println(), so its very simple and no user interface is needed.
The guessing of words is done with eclipse. Now I need to add a function, which will allow the user to exit the "program" anytime by clicking CTRL+z and when they do that I'll need also to print out possible words they could've have guessed.
But I do not know how to add the CTRL+z exit function. Can anyone suggest anything on how to ? The word guessing is a loop.

You're answer is simple:
You can't do that!
Because you're using a command-line window. In command-line there is no listeners like KeyListener or MouseListener.....
If you want to do so, leave the command-line and go learn Swing in java.
See this question: How to get input without pressing enter every time?

Related

how can we simulate Ctrl+C to stop the console app from waiting for user input in java

I am trying to test a command line app that waits for the user input after every step. I am able to test the app using System Rules provided by Stefan Birkner. Currently, I provide inputs from the beginning to the end which works like a charm and I can assert the final output from system log.
However, I want to test for the negative cases before the end of the app for which I give invalid inputs in the beginning to evaluate the error message. When invalid inputs are given, the console prints an error message and keeps waiting for the user to provide a valid input. How do I send Ctrl+C using as shown below:
systemInMock.provideLines(Ctrl+C);
systemInMock.provideLines accepts only strings. Is there a way to send Ctrl+C signal?
An example of my junit test is shown below:
#Test
public void testInValidMarker() throws Exception{
systemInMock.provideLines("abc","def","1");
Main.main(new String[]{});
assertTrue(systemOutRule.getLog().contains("Invalid marker, try again"));
}
Appreciate your help!
If I'm not mistaken, when you do ctrl+c, it doesn't actually get written to console. If that's true, then in no case will your program ever be given ctrl+c, so provideLines will never be in a position where it is given ctrl+c.
For proof, open up cmd and type in a program with program arguments (in my case, I use ant). If you type ant and then ctrl+c, the cursor is moved to a new line.
There are two ways you can control termination behavior:
You can use a shutdown hook (found from this previously asked question ). Doing this will allow you to handle what happens (potentially with issues).
Or you could create your own termination argument like -q or q, which would trigger an action to end the program (maybe a System.exit(1)). This way you can mock that input.
In UNIX/Linux, when you type CTRL-C, your shell intercepts it and sends the process a SIGINT signal -- see: How does Ctrl-C terminate a child process?
Therefore the System Rules project doesn't have anything to help you -- in this situation the process doesn't receive any character input.
By default, the whole JVM shuts down when it receives SIGINT. This is obviously bad news for a running test.
The SO question Signal handling using "TERM" -- may be of use.
A side effect of Java's portability is that for some OS features, it either abstracts things away until they're unrecognisable, or doesn't expose them at all.
I suspect what you're asking for can't be achieved.
If you're allowed to change the requirements slightly, you could ask the user to close with CTRL-D -- this closes stdin with EOF.
Although it's quite the overkill, you could launch a whole new JVM running your program, using ProcessBuilder. You might imagine you'd get an API to send arbitrary signals to that process. But for portability reasons, all you can do is process.destroy(), which sends SIGTERM.
Tried this as a comment, but it didn't read right. It's not exactly an "Answer" though.
So Java is really bad at console input. It reads an entire line at once and you can't do anything about it--there is no way to trap special characters or even see any of the input before the user hits return. Also I think a ctrl-d will close your input session--(Add that test to your use case if you don't use any other suggestion here because it can put you into a state you didn't expect!)
Three suggestions:
The simplest: If you can use a GUI and aren't really looking for an ongoing input/response REPL the simplest answer is usually to use JOptionPane to throw up a quick dialog. It's a one-line solution to get some user input, but not so good for an ongoing command-driven system.
If you can't use swing (If you are running headless) then you may have little choice, but you can use the JLine library. That will give you a lot more flexibility. This is how Groovysh does it's REPL. It will let you see each character as it is typed and do things like completion where a user might type part of a file name and hit tab and you put the rest in for him.
If you don't want to use JLine but want a REPL feel there is also a more complex GUI solution--create a swing console window. A trivial solution would just be a text input box to allow typing and a text area to display results, but there are certainly libraries out there with more complete console solutions.
The point here is that using Java standard input alone is just not a good solution for anything beyond a trivial/personal script--and even then I avoid it. Perhaps not the answer you asked for, but maybe it's the one you need :)

Java CLI App - keep input from scrolling up

I get that this isn't possible to do with normal java, although if there are any libraries out this it would be very useful.
Essentially, I'm designing a console app and running into an issue that when output happens while something is typed in the input line, that input text will move up and appear before the line that just got output. Is it possible to fix this in some form so that the text you are inputting that stays at the bottom?
EX:
I'm typing something as input into my commandline app, and then the program prints something WHILE I'm typing - this causes what was originally on the input line to be scrolled up with whatever the output text was. When you are trying to type something in this can obviously be detrimental. I know it's possible to prevent this.. (Other programs have done it... EX: Minecraft Server)
(If I need to be more descriptive I can.)
You could use the help of threads. One that listens to user input, the other process the actual output. This problem is similar to basic race condition problems when multiple threads attempt to read and write to a shared resource.
Your shared resource is that console. You need to keep the Input/Output operations synchronized. Have a look at race condition.

How to write an equivalent of KeyListener with JLine?

I am working on a console application written in Java. What I have to do is handle user keyboard input. When a long process in launched with our program in a terminal, the user must have the possibility to press 'q' at anytime to stop the process (which is running on a separate thread).
I've tried several things :
Running in another different thread something that read user input and throws an InterruptedException to the process' thread
Using JLine and its ConsoleReader
Using JLine and add a TriggeredAction linked to a keyboard key
But each time, I face the same problem : the user has to press ENTER key, and I don't want that.
Thanks for help if you have any ideas, or the actual solution of my problem.
PS : Please, if you think this is impossible, don't answer. I know it's possible.
Perhaps you could use one of these libraries,
http://sourceforge.net/projects/jxgrabkey/ for linux
https://code.google.com/p/jintellitype/ for windows
Less related with your question, but I think can help you,
http://sourceforge.net/projects/javacurses/
The problem, with all of this, is that you will lost the platform independence.
To avoid having the user press enter and to be able to directly respond to a keypress, we can make use of jline3 in the following way, wherein we first change the terminal into rawmode to directly respond to keys, and then wait for the next entered character.
var terminal = TerminalBuilder.terminal()
terminal.enterRawMode()
var reader = terminal.reader()
var c = reader.read()
<dependency>
<groupId>org.jline</groupId>
<artifactId>jline</artifactId>
<version>3.12.3</version>
</dependency>

Taking input from a text field in one class and scanning it in a different class

I am trying to make a GUI for a program I have completed and do not want to modify. My problem is the program uses a scanner to get user input and I don't know how to get input from the GUI to the scanner. I know how to use getText() from a text field in the GUI but that doesn't update the scanner so the main program just waits for that input and doesn't continue.
"I am trying to make a GUI for a program I have completed and do not want to modify."
When you give restrictions such as this, it is usually a good idea to explain more, such as the reasons for the restriction; this understanding often helps us give better answers.
"My problem is the program uses a scanner to get user input and I don't know how to get input from the GUI to the scanner. I know how to use getText() from a text field in the GUI but that doesn't update the scanner so the main program just waits for that input and doesn't continue."
You are trying to do what is next to impossible. The solution: correct your console class so that the user interface portion is separated out, a la MVC, so that the model can be used for either a console program or a GUI program.
So the simple answer is: don't try to do this. Create a well behaved set of classes with decent separation of concerns so that you can re-use classes well.

Java Stream Keyboard Input

I am writing a program that takes commands via the console.
However, I do not want to press "enter" in order to send that command.
I want the code to constantly monitor what I am entering, and execute the code when I am finished.
The commands are coming as text from a speech recognition program, therefore, eliminating the need for the "enter" stroke is pretty key.
Any one have any ideas?
I have recently come to the knowledge of events in java and i believe this would help you. You would just need to associate the speech recognition printing to the screen with an event in java and it would have a listener to listen for the event and when it sees the event it would execute your desired code. I currently have a thread opened where im trying to get some good examples of this, perhaps that will help.
Java Events Question
Already answered here:
How to read a single char from the console in Java (as the user types it)?
No portable way to do it, depends on your platform.
I haven't worked with Java since college, but if you're reading from the command line, then you are using System.in.read() or something similar. Since these are blocking method calls, your application will never be notified about the new input until ENTER is pressed.
If I'm dead wrong, please let me know.
You're probably better off using a simple (possibly even hidden) that can take the user text and an event listener on the UI element that reads it in to the application's text processor.

Categories