Java lanterna - Cannot read user input - java

I have problems with reading user input from java lanterna library terminal. Upon key strike I would like the system to print a certain character on the terminal. I use this code:
public class Snake {
public static void main(String[] args) {
Terminal terminal = TerminalFacade.createTerminal(System.in, System.out, Charset.forName("UTF8"));
terminal.enterPrivateMode();
Key key =terminal.readInput();
if (key.getKind() == Key.Kind.Tab)
{
terminal.moveCursor(100, 100);
terminal.putCharacter('D');
}
}
}
Unfortunately, I only have terminal opened - I cannot do any input. Anybody has an idea why this happens?

Based on the given code, it seems that you are only running through your if statement once before the main method is finished executing.
Try implementing a while loop to continuously search for input like so:
public static void main(String[] args) {
Terminal terminal = TerminalFacade.createTerminal(System.in, System.out, Charset.forName("UTF8"));
terminal.enterPrivateMode();
// I would recommend changing "true" to a boolean variable that you can flip with a key press.
// For example, the "esc" key to exit the while loop and close the program
Key key;
while(true){
// Read input
key = terminal.readInput();
// Check the input for the "tab" key
if (key.getKind() == Key.Kind.Tab){
terminal.moveCursor(100, 100);
terminal.putCharacter('D');
}
}
terminal.exitPrivateMode();
}
Additionally, check out the Lanterna development guide.

Related

Loop in Java until the user presses any key (not just the Enter key) in a console app [duplicate]

I want to execute a certain function when a user presses a key. This will be run in the console, and the code is in Java. How do I do this? I have almost zero knowledge of key presses/keydowns, so I could really use an explanation as well.
You can't detect an event in the command line environment. You should provide a GUI, and then you can use the KeyListener class to detect a keyboard event.
Alternatively you can read commands from standard input and then execute a proper function.
If you want to play with the console, you can start with this:
import java.util.Scanner;
public class ScannerTest {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
boolean exit = false;
while (!exit) {
System.out.println("Enter command (quit to exit):");
String input = keyboard.nextLine();
if(input != null) {
System.out.println("Your input is : " + input);
if ("quit".equals(input)) {
System.out.println("Exit programm");
exit = true;
} else if ("x".equals(input)) {
//Do something
}
}
}
keyboard.close();
}
}
Simply run ScannerTest and type any text, followed by 'enter'

Getting input from users command and using .equals

Im trying to read the users input from the command box of my program and based on what the user enters into this command box the program should output appropriate messages. For example when the user enters quit the program is supposed to stop and I have implemented this correctly. SO what I am trying to achieve is when the users doesnt enter the words :"QUIT", "ROLL","property", "Buy" , "help" "done ,"balance" the program should displau an error message.
I need the command to work simultaneously so that if any 7 commands entered an appropriate message is returned
Here is my code so far:Thanks ,
private void echo () {
String command ;
String command2;
ui.display();
ui.displayString("ECHO MODE");
do {
command = ui.getCommand();
ui.displayString(command);
} while (!command.equals("quit"));
{
ui.displayString("The game is over.");
}
do{
command = ui.getCommand();
ui.displayString(command);
}while (!command.equals("help")||(!command.equals("buy"))||(!command.equals("roll"))||(!command.equals("done"))||(!command.equals("property"))||(!command.equals("balance")));
{
ui.displayString("Please enter a valid command");
}
return;
Your last do/while's condition looks almost good, but it should be using && instead of || : you want to display the error message when the command input isn't the first expected one, and not the second expected one, etc.
A prettier syntax would be to use a List of accepted commands and check whether it contains the received command :
List<String> acceptedCommands = new ArrayList<>();
acceptedCommands.add("help");
acceptedCommands.add("quit");
// [...]
do { command = ui.getCommand(); }
while (!acceptedCommands.contains(command));
Note that the do/while construct is rarely used (altough it can sometime be more appropriate than a standard while) and that you seem to misuse it ; you've used twice that same pattern :
do { actions }
while (condition)
{ more actions }
This is probably not doing what you want, since the last block isn't part of the do/while but just an anonymous code block, with its own scope but not much else.
After discussion I think you want something along those lines :
private void echo() {
String command = null;
while (!"quit".equals(command)) {
command = ui.getCommand();
if (!acceptedCommands.contains(command)) {
ui.displayString("Please enter a valid command");
} else if (!"quit".equals(command)) {
// handle other commands
}
}
ui.displayString("The game is over.");
// no need for "return;", it's implicit
}

IDE output different from command line

I've wrote a programme to mask the input that a user types in at the command line.
In detail:
When my programme starts, I run a new thread that prints out an asterisk every millisecond via System.out.print("\010*").
Meanwhile my main method reads in the users input via read.nextLine().
When I run this programme in eclipse, the output is an overflow of asterisks (which is what I would expect).
However, when I run this programme from my terminal, I only see an asterisk appear whenever I type a character.
Why is this? I read some other articles saying how the CPU only allocates 6-10% of memory to the command line, whereas a typical IDE gets more than twice this.
My code is shown below just for reference:
import java.util.Scanner;
public class Main {
public static void main(String [] args){
PasswordMasker passwordMasker = new PasswordMasker();
passwordMasker.start();
Scanner scan = new Scanner(System.in);
String password = scan.nextLine();
passwordMasker.stopMasking();
System.out.println("The password is: " + password);
}
}
public class PasswordMasker extends Thread {
private boolean maskInProgress = true;
public void run(){
mask();
}
private void mask() {
while(maskInProgress){
try {
Thread.sleep(1);
System.out.print("\010*");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Masking stopped");
}
public void stopMasking(){
this.maskInProgress = false;
}
}
Because the Eclipse console can't display backspace character (\b or \010),
because of bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=76936
The cmd can display it, that is why your program works as expected in cmd.
However the fix will be available in Eclipse 4.5 M4, according to the bug report.

My console is flashing - Java - Eclipse

When I am running a simple java program in eclipse, when I run it, the console flashes what it should, then it disappears.
public class apples {
public static void main(String[] args) {
int age = 60;
if (age < 50) {
System.out.println("You are young");
} else {
System.out.println("You are old");
}
}
}
Your program is immediately terminating after printing what needed to be printed. You can use several methods to keep the console on the screen.
Your program is immediately terminating after printing what needed to be printed. You can use several methods to keep the console on the screen. One possibility is to use
while(true);
to stop the application from exiting. Beware that you should only use this for debugging methods!
Another, probably better, way is to ask for input before closing the window.
Simply read a line from standard input. Your program will wait until you type something and only then exit.
Scanner sc = new Scanner(System.in); // create a scanner that will read from standard input
String s = sc.nextLine(); // You don't even need to save the return value of
// sc.nextLine() here

why my program never reach the solve method?

sorry if its a stupid question, but I a beginner using StreamTokenizer, I am trying to solve this exercise this, please help me, I dont know what its wrong in my program that never reach my solve method, it also never finishes, I already ask in timus forum, but I know that here is faster to receive an answers
import java.io.*;
public class Prueba {
static int index = 0;
static double[] l = new double[131072];
public static void main(String args[]) throws IOException {
StreamTokenizer str = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
while (((str.nextToken() != StreamTokenizer.TT_EOF))) {
if (str.ttype == StreamTokenizer.TT_NUMBER) {
l[index++] = str.nval;
//System.out.println(str.nval);
// System.out.println(l[0]);
// System.out.println(l[1]);
}
}
solve();
}
public static void solve() {
double res;
for (int i = index - 1; i >= 0; i--) {
res = Math.sqrt(l[i]);
System.out.println(String.format("%.4f\n", res));
}
}
}
You are reading from the standard input, and your code loops until it gets a TT_EOF. To feed a TT_EOF into your program, you need to press Ctrl-D if you're using Unix, or Ctrl-Z followed by Enter if you're using Windows.
You are waiting on System.in, it is blocking on read, ergo, you will never get to EOF so you while loop will continue to wait for input.
As it is, you either need to pipe a file from command line, or enter text on console followed by EOF character. Pressing Ctrl+Z generates EOF in Windows, and pressing Ctrl+D generates EOF in Unix/Linux.
EDIT: If your input is single line you can check for TT_EOL instead of TT_EOF.
You must call eolIsSignificant(true) before entering the loop. This will make sure end-of-line is treated as separate token

Categories

Resources