Pausing Java Code (Netbeans), then Resuming Execution - java

So I'm looking for a similar statement to C++: System("pause");
That runs the code up until a certain point, await's user/keyboard input to continue [Enter], then proceeds.
Everything I can find talks about kill commands, exit systems, threads, etc that basically just close the program down (useful if it's stuck but not for my purposes). The only other references I could find here were to literally pause the program for a set amount of time.

The best way is to use Scanner class. You can do it like this:
System.out.println("Press enter to continue");
new Scanner(System.in).nextLine();

Related

Reading from keyboard and ignoring printed text

I am writing a java program (In Intellij) that accepts a command from the user and reacts to the command. The reaction is asynchronous (using a separate thread).
Scanner in = new Scanner(System.in);
String command = null;
do {
System.out.println("Enter command or q to exit: ");
command = in.nextLine();
System.out.println("Received "+command);
obj.react(command);
}while (!command.equals("q"));
The reacting object may take a while to react and prints a message after it finishes.
The problem is that if I start typing a command, and before I finish, the object prints something, the typed command is lost.
For example Here is a problematic scenario (The text in italics is the user input):
Enter command or q to exit:
go
Received go
goAgainobj finished reacting!
Received
In this case, when I Hit enter after the printed message, the received command is empty.
Is there any way to keep the typed characters even after something was printed?
If you use an actual console, printed output will not affect written input. If you type 'go' and the system prints 'Again', then the in-buffer still knows 'go'. This is unintuitive and bad to read, but it's practical to interrupt running scripts, or other programs.
This may already work on your IDE or your system, depending on OS ans IDE.
If you want something more 'pretty' then you need to fully control input and output, much like the 'top' command in linux (if you happen to know that).
You can handle this way of input better with the Console class. See: https://www.codejava.net/java-se/file-io/3-ways-for-reading-input-from-the-user-in-the-console #3
The most intuitive idea to solve your problem seems to read, and then remove all input at the time you want to print something, and reprint it, so you'd get:
> go
received go
obj finished reacting!
> go
...
You'd basically always print an input line yourself, after first reading and removing the already printed input. This is why you need the Console class, because there, input and output are synchronized, so if you print something, you know that no input will happen in the meantime.

Proper way to receive user input in Android and then continue execution

I am implementing an Interpreter for a moderately simple Pascal/BASIC-like programming language, in Android. I have finished the parser, so programs get recognized, loaded in memory and ready to execute. The language is procedural, emulating command line input/output and obviously not event-driven like Java in Android.
A sample program may look like this:
FOR i FROM 1 TO 10
READ Name
PRINT "User ", i, " name: ", Name
END_LOOP
Being relatively new to Android, I did not know that Android dialogs are asynchronous, and thus cannot interrupt execution, as explained in dozens of similar questions. (1), (2), (3), (4)
So, I initially thought I would implement READ commands by showing a modal Dialog. Executing code that involves reading input from the user, would require waiting for it to finish before moving on to the next line of code. But this should not be done with a dialog, as mentioned in the above posts.
I figured out that the most "appropriate" way would be to "save" the execution state of the whole program, stop execution and then start executing by loading the last state, when user inputs something from the Dialog. But this seems impossible, and way too much hassle for such a simple task. Is there an easier way?
Any suggestions are welcome.
I did not know that Android dialogs are asynchronous, and thus cannot interrupt execution, as explained in dozens of similar questions
All Android UI is asynchronous.
I initially thought I would implement READ commands by showing a modal Dialog.
There is nothing intrinsically wrong with this. However, READ would need to suspend execution of your interpreter until the user has completed the dialog.
Is there an easier way?
Off the cuff...
Step #1: Run your interpreter on a background thread.
Step #2: Have your READ code invoke your dialog on the main application thread, then block on a Semaphore to block your background thread.
Step #3: Have your dialog code get the results of the user input over to your interpreter by some means, then release the Semaphore when the dialog goes away.
Step #4: Your interpreter code continues.

Modify Control C Command Signal to Allow Input

Upon pressing Control C on the command prompt, is there a possibility of interrupting this signal, and prompting the user for input, to confirm they want to exit the program? I am aware that there are signal interrupts, but not on how to modify the signal to allow input.
String user;
Scanner input = new Scanner(System.in);
try {
[...] // Some code
}
catch(NoSuchElementException e) {
System.out.println("You have chosen to exit the program using Control C.\n");
System.out.print("Are you sure you want to exit? Type Yes or No.");
user = input.nextLine();
if(user.equals("yes")) {
System.exit(0);
}
else {
[...] // Return to the main menu
}
Currently, this code catches the Control C signal, outputs the String: "Are you sure you want to exit? [..]" but then refuses to accept input from the user. It waits a second, then the program would exit instead of getting the input from the user to confirm their decision.
However, I want the code to request input from the user upon Control C activation, and if it is yes, exit the program, else return to the main menu, which it seems to not work as intended.
The short answer is: You should really not do that. There is no portable way to prevent an interrupt signal from exiting a Java application.
The longer answer is that might be possible using internal classes such as sun.misc.Signal and sun.misc.SignalHandler. Since these classes are not portable across JVM implementations and may change in later versions you should avoid using them.
What you should do is to provide another standard way of exiting the application such as typing quit and require confirmation when receiving that input.
If you really want to avoid users exiting with ctrl+c you could try running java with -Xrs which should disable the handling of the console signal (NB: I have not tested this and am not really sure how it works)

Pausing program until next startup

I have a program which bruteforces an AES256 encryption, how would I pause the program when the computer goes into shutdown/or reboot and continue at the same point until the next boot of the system?
A sort of hibernate of the program.
I would agree with part 2 and 3 of #Thufir's answer, but regarding part 1 it assumes that you are running a GUI.
Instead of this I would add a shutdown hook into the JVM and write the state of my program at that point. You can do this using the following:
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
// your serialization code goes here
}
});
You asked three things here.
1- How can I check when the OS goes reboot/shutdown
Solution:
You can make an empty invisible window, and add WindowListener to it. It will receive windowClosing event on windows.
You can find an example HERE
2- How can I save the state of my BruteForce process and pause to start again when system goes up.
Solution:
Here is easy, you must serialize. These will save the state of your class/classes to deserialize when system goes UP again. You can study HERE
3- How know when startup the programm again when OS goes UP?
Solution:
You can put your program in initialization process of your OS. When it starts, you check if there is anything to deserialize and do it, restoring the process of the BruteForce.

Java console application clean up

I have, a game bot which runs through console. I don't think i'm going to code a gui for it but i would like to have the possibility to close the program without CTRL+C cause this just interrupts my program instead of properly cleaning up the code and ensure that theres no leaks.
Should i use som kind of Key Bindings or am i bound to, make a GUI ?
Or how could i go about this ?
I think thats what a shutdown hook is for.
Runtime.getRuntime().addShutdownHook( new Thread() {
#Override
public void run() {
System.out.println("Application shutdown");
}
});
David's answer is good. It may well work for you.
I generally prefer not to deliberately abort a process and then detect that it's coming down to avoid dangling operations. So I'd probably do more like:
Are you processing console inputs as they are entered? IF so, you could just have a console command that tells the app to shut down, and check for this in whatever your process is of handling console inputs. Or if you mean that the app just runs with no user input, you could just periodically check if the console buffer is empty (Console.reader().ready()), and if not, read the console and see if it's the quit command.

Categories

Resources