(Java) How to get user input without pressing the "enter" key [duplicate] - java

This question already has answers here:
How to read a single char from the console in Java (as the user types it)?
(7 answers)
Closed 3 years ago.
I was curious and wanted to test this type of thing out in java. I looked it up online and couldn't really find anything that helped out in any of the questions I found; so I decided to ask it myself.
In the example I wrote out, you're given a couple of options and you get user input and then stuff happens based off of user input using a switch statement. Doesn't really matter what happens as I'm trying to figure out how to get user input without having to press enter.
So, for example, if the user has to choose between 1, 2, 3, 4, or 5 for input, when the user presses '2', for example, the program reads this input instantly without them having to press enter. Is there any way to do this? I'm using cmd on Windows 10 as well (thought about it when I was doing a project on NetBeans though, this shouldn't make a difference I don't think).
Thanks in advance!

You can do something like this:
import java.io.IOException;
public class MainClass {
public static void main(String[] args) {
int inChar;
System.out.println("Enter a Character:");
try {
inChar = System.in.read();
System.out.print("You entered ");
System.out.println(inChar);
}
catch (IOException e){
System.out.println("Error reading from user");
}
}
}
so the command
System.in.read()
will read the char that the user have been entered.

Related

How do I mask passwords in a command-line Java program with asterisks or the like?

The standard JVM method for reading a password from the command line without showing it is java.io.Console.readPassword(). This, however, shows nothing while the user is typing; users accustomed to graphical programs will expect symbols such as "•" or "*" to appear in place of the characters they type. Naturally, they will also want backspacing, inserting, and so on to work as normal, just with all the characters being operated on replaced with the same symbol.
In 2019, is there a generally accepted JVM procedure for showing "*******" when the user types "hunter2" in a console application? Can this even be done properly without a GUI? A 2011 SO question on the topic got an answer linking to this article on the topic; can we do better nowadays than the rather elaborate solution shown therein?
(I happen to be using Kotlin as my language of choice, so a Kotlin-specific solution will satisfy if there is one.)
hunter2? Wow. Reference acknowledged.
There is no easy way. The primary problem is that the standard System.in doesn't give you any characters at all until the user has pressed enter, so there's no way to emulate it (if you try to read char-for-char from System.in and emit a * every time a key is pressed, that won't work).
The lanterna library at https://github.com/mabe02/lanterna can do it, though. If you want to emulate it, it's.. very complicated. It has branching code paths for unix and windows. For example, on unix, it uses some hackery to figure out what tty you're on, and then opens the right /dev/tty device. With lanterna, writing this yourself would be trivial.
It's that or accept Console.readPassword()'s blank nothingness, really. Or, write a web interface or a swing/awt/javafx GUI.
I think answer to your question can be found here in stackoverflow itself.
please see this:
masking-password-input-from-the-console-java
sample code from there:
import java.io.Console;
public class Main {
public void passwordExample() {
Console console = System.console();
if (console == null) {
System.out.println("Couldn't get Console instance");
System.exit(0);
}
console.printf("Testing password%n");
char passwordArray[] = console.readPassword("Enter your secret password: ");
console.printf("Password entered was: %s%n", new String(passwordArray));
}
public static void main(String[] args) {
new Main().passwordExample();
}
}
hope this is helpful. :)

Design Pattern in Java for Getting Input and Acting on it

I'm trying to make a tic-tac-toe game and I'm encountering a lot of copy-paste work for inputs. I'm trying to figure out what design pattern and implementation works for prompting the user, collecting their input, comparing it and then acting by assigning a value. Right now my code looks like this.
public void promptPlayerCount(BufferedReader in) throws IOException {
String input;
// initial prompt
System.out.println("How many players?");
input = "try again";
while (input.equals("try again")) {
input = in.readLine();
// extract data and check it
switch (Integer.parseInt(input)) {
case 1:
// assignment
playerCount = 1;
break;
case 2:
playerCount = 2;
break;
default:
input = "try again";
// clarified instructions
System.out.println("please enter 1 or 2");
}
}
}
There's a part of me that thinks I could make a function (maybe a factory?) that allows me to generate a function by passing the constructing function the details of the initial prompt, the extraction method, the assignment action and the clarification message.
Would this be best done with lambda functions?
Text input is hard, especially if you can't trust your user (like in a game). Your parseInt will throw a nasty exception right off if your value isn't an integer.
Also standard in is not friendly. I assume this is for an assignment so I won't fault you for using it, but in anything where you don't HAVE to use stdin, don't. The problem is that it's amazingly difficult to get Java to respond to anything less than an entire line with an enter at the end.
When dealing with user input I almost always trim it (Just because they love to insert random white spaces at the beginnings and end) and check to see if it's empty. This could probably be put into a function that also either shows an error or exits the program on "Empty" and otherwise returns a string.
If you often want int values, write a second function that calls the first. Have the second function return an int, but have it catch the exception if the text is invalid and prompt the user again. You could even have this function take a "Range" of integers as a parameter and provide a prompt. So what you have above could look like this:
playerCount = getUserInput("Please enter the number of users", 1, 2);
The rest is wrapped in simple non-redundant functions.
Won't write the code for you because A) it's probably a homework assignment and the fun part is actually coding it and B) someone else probably will provide a full solution with code before I'm done typing this :(
Good luck.

Java program to display character instantly [duplicate]

This question already has answers here:
How to read a single char from the console in Java (as the user types it)?
(7 answers)
Closed 7 years ago.
I want to write a program which instantly displays a character when it is typed in console. For example, output asks 'Enter'. Suppose I write char 'g' in console. It should instantly display in console. Also, after entering char, I don't want to press enter. Please explain to me how can I achieve this and also explain the concept.
I have tried this code:
import java.io.*;
public class input {
public static void main(String[] args) throws IOException {
InputStreamReader ir=new InputStreamReader(System.in);
System.out.println(ir.read());
}
}
Depending on the development environment, System.console() may return null. Personally, I'm not sure what's the safest way to go about instantiating some kind of "mock" console in this case.
Although, you can create the illusion of this by using a native key listener like JNativeHook, which listens for key strokes without a GUI. Once a key is a pressed, you can print to the console using System.out.print. This also ensures that when they user types a key, it's not entered twice (once for the user to enter it, and another time for displaying it). Technically, the console already displays letters as soon as the user types it ;)
String randomWords;
Scanner kb = new Scanner(System.in);
System.out.print("Please enter words: ");
randomWords = kb.nextLine();
System.out.println(randomWords);
If you want to continuously get and print text then put the last two lines in a loop.

Entering Data into jGrasp without using a GUI

My class got a Java programming project today in class and the program we are using is jGrasp, I know that I can handle the pieces of this project except for one aspect.
The project requires the user to enter data into the program (i.e. answer a question), but for this Semester we are not using GUIs so I can't create a GUI for the user to input the data or answer.
I'd like to know how could the user enter data into jGrasp without using a GUI?
Thanks for taking the time to read this post, and I'd greatly appreciate any help you could give me.
I hope I'm helpful :) it's funny that I want to know about the same thing in GUI & you want to know without it :D ....well i can solve your matter I believe :)
From the starting,
Example:
import java.util.*;
public class Assignment //class name
{
static Scanner stdIn = new Scanner(System.in);
public static void main(String[]args)
{
int A, B; //Intialize variables as normal
System.out.print("Enter a question you want to ask "); //Between the double quotes " " you type anything you want to type :)
A = stdIn.nextInt();
: //
: // complete your program
System.out.println("Add the statement for giving the result "+B); // "+B" for inserting the answer along with your result statement
}
}
Note: In the statements,
System.out.print();
System.out.println();
These statement work similarly.... just the difference is statement with "print" is displayed on the same line & Statement with "println" is displayed in next line....when you will try you will understand ...just for avoiding confusion why I have written so I'm mentioning it :)
I hope this helps...tczz :)

BlueJ is trying to run my Java program forever

I've just started learning Java (I am a C#.NET programmer as well). I am trying to get multiple user inputs and add them to an array. After this, I calculate the average from the given values.
For some reason, BlueJ will try to run my Java program forever. Meaning, It will keep showing the progress bar and will not open any console window.
I'm not sure if it's something wrong with my code, or BlueJ, because I've never encountered a problem such as this one before.
Here is my code:
import java.util.Scanner;
public class Problem22 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int inputs = 2;
int[] values = new int[3];
while (inputs > -1) {
values[inputs] = scanner.nextInt();
inputs--;
}
System.out.println(averageValue(values));
}
private static int averageValue(int[] values) {
int sum = 0;
for (int i : values) {
sum += i;
}
return (sum / values.length);
}
}
Please help me try and find a solution.
It seems that in BlueJ, you have to supply output before you ask for input. It's quite a weird bug.
More info:
http://www.bluej.org/help/faq.html#hangoninput
Your code worked for me in Eclipse, but I had to realize what I was supposed to do, enter three ints.
It is generally better to prompt the user for input. This may be a bug in BlueJ, but it's not too bad to have to output a prompt before asking for input. It's just generally a good thing to do.
Link to my version of the code with prompts:
https://gist.github.com/kaydell/6552282
I believe that the only reason not to prompt for input is if you are reading input from a file or something. When your program is interactive with the user, your programs should prompt the user for input.
The code compiles just fine for me in IntelliJ IDEA, and also runs fine. so I would assume it's a BlueJ bug.
Here is an example input and output after running it (pressing enter after each input line)
3
4
5
4
(which means by the way your code works correctly, 4 is the average of 3,4,5...)
Which version of BlueJ are you using? I assume restart to BlueJ or even your machine didn't work?
Terminal window opens only when there is an output. Th program has asked only for input. Therefore it is terminal window isn't opening. Replace your snippet by this one:
`while (inputs > -1)
{
System.out.println("Input number - "+inputs);
values[inputs] = scanner.nextInt();
inputs--;
}`
I hope you will see the terminal window.

Categories