Java program to display character instantly [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 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.

Related

Not sure why my for loop isn't working the way i intended it to

So, before I start I just wanted to say that I'm very new to Java as a language and I've been reading a text book that was recommended to me.
One of the examples provided within the text book on for loops had the following code, which is meant to generate an infinite for loop until the user presses the character 'S' on their keyboard.
Here is the code:
class ForTest {
public static void main(String args[])
throws java.io.IOException {
int i;
System.out.println("Press S to stop.");
for (i = 0; (char) System.in.read() != 'S'; i++)
System.out.println("Pass #" + i);
}
}
I copied the code exactly as it was written within the book but when I run the program, to my surprise, it doesn't start printing out numbers onto the console. Additionally, whenever I press any keys on the keyboard it generates three numbers within the sequence. Example shown below:
I have also included a screenshot of the code from the book below:
I was wondering whether anyone knows why this is the case!
Any help would be greatly appreciated thanks.
The reason it's printing multiple times is because multiple characters are detected.
In your case, it's printing twice because you entered a value (Pass 1) and a new line (Pass 2)
The problem you have is not with System.in.read(), but because the console is usually using a buffered approach. Meaning that data is only transferred to the System.in.read() once you press enter.
So to get the example working, you would have to switch the console to an unbuffered mode, but there is no portable way to do this, because there are so much different types of consoles. Maybe have a look at what editor/console the book is using
This block of code looks like it was written by someone who was deliberately trying to make it obtuse and difficult to comprehend for a beginner.
The middle expression of a for statement is the criterion for taking the next step of the loop. It is evaluated before each step of the loop to determine whether the for loop is complete yet. In this case, it calls in.read() and checks if the input is S before each step of the loop.
in.read() waits for the next line of input it gets. When you enter a value and press Enter, that line gets read, so the loop takes a step. And a new line is also entered, so the loop takes a second step.
It will not print lines to the console unless you enter lines, because in.read() causes the program to block (wait) for the next input.

ArrayList<Integer> is not storing user-inputted integers in Java 8 (1.8)

*EDIT - SOLVED: After instantiating the Scanner Object, I used a delimiter as follows:
scanner.useDelimiter("");
Prior to this, I did try a delimiter that looked something like this (the exact code is available on Stack Overflow):
scanner.useDelimiter("\\p{javaWhitespace}");
...but it didn't work very well.
Thank you, everyone. If you're having this very same issue, try the first delimiter. If it doesn't work, upgrade your JDK to 13 then try it again.
Ok, my goal is to have a user input a credit card number which I would then like to store in an ArrayList of Integers and subsequently pass this list to my functions which will perform the Luhn algorithm in order to validate the provided number. Once the user presses Enter, the processing begins. This is a console application, nothing fancy.
Everything works beautifully...except the user-input part. None of the user-input is being stored into the declared ArrayList. I've inserted a print message to give me the size of the list just after the pertinent while-loop and....yep, 0. I also pass this list into a custom lengthChecker(ArrayList<Integer> list){} function subsequent to the relevant while-loop and it's printing my custom error-message.
I have declared local int variables within the scope of the while-loop and that wasn't helping much. I have tried getting the user's input as Strings and storing them in an ArrayList<String> list; then parsing the input but that didn't work very well (especially as I need the Enter key to behave as a delimiter such that the next steps can take place)
Anyways, here is the code to the function in question. Am I missing something obvious or should I just quit programming?
public void userInput() {
Scanner scanner = new Scanner(System.in);
List<Integer> list = new ArrayList<Integer>();
System.out.println("Please input the card-number to be checked then press Enter: ");
while(scanner.hasNextInt()) {
list.add(scanner.nextInt());
}
System.out.println("Length of list: " + list.size());
listLengthChecker(list);
scanner.close();
}
Thank you in advance.
I don't have the full context on all the code you've written to be able to solve your problem, but I can guess at what's going on. If you want to run any user I/O (such as the scanner), it must occur within the main method. I can only assume that you run your userInput() function within the main method in your class. However, because your userInput() function doesn't have the static keyword in its definition, it can't be accessed without initialising an object of the class - but as far as I can tell from your code, there is no object that the method could refer to. Add the static keyword (i.e. initialise the method as public static void userInput()) to be able to run the function as you intend.
As for the while loop - there's a small chance that this is a difference in Java versions (I use Java 11), but while(scanner.hasNextInt()) won't stop being true at the end of your line or when you press enter - only when you insert something (such as a character) that cannot be interpreted as an integer.
This while loop untill you enter any non integer value.
You finished entering all the integer values and then your program will print your list elements.

(Java) How to get user input without pressing the "enter" key [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 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.

How do I make a program with multiple classes run until the user specifies "E" instead of terminating at the end of Main?

I'm working on a program that allows a user to read a file, search for specific text (still in progress) in a file and write (append) to a file. The program has four classes, with one method in each, corresponding to each of the functions of the program.
My first class (containing Main) prompts the user to specify whether they want to read/search/write to a default file. Like so:
public class SimpleDBFunction {
public static void main(String args[]) throws IOException{
//Prompt user to provide input in accordance with desired function
System.out.println("Type 'R' to read a file; 'S' to search for text within a file; 'W' to write to a file; 'E' to exit");
//Initialize scanner and a string variable to hold the value of scanner variable
Scanner iChoice = new Scanner(System.in); //iChoice - inputChoice
String userChoice = iChoice.next();
//If user specifies "r" go to fileReader class
if(userChoice.equalsIgnoreCase("r")){
SimpleDBReader sdbrObject = new SimpleDBReader();
sdbrObject.sdbReader(args);
//If user specifies "s" go to textSearch class
}else if(userChoice.equalsIgnoreCase("s")){
SimpleDBSearch sdbsObject = new SimpleDBSearch();
sdbsObject.sdbSearch(args);
//If user specifies "w" go to fileWriter class
}else if(userChoice.equalsIgnoreCase("w")){
SimpleDBWriter sdbwObject = new SimpleDBWriter();
sdbwObject.sdbWriter(args);
//If user specifies "e" terminate program
}else if(userChoice.equalsIgnoreCase("e")){
System.exit(0);
}
iChoice.close(); //Close scanner, probably redundant here
}
}
The specific issue I have is that I want the program to run in this "state" of awaiting user input, even after the user has already prompted the program to perform one of the actions. I have tried to use both a while loop, and a do-while loop, to achieve this; but both ended up infinitely repeating whichever function the user specifies instead of running it once and returning to main. I also tried to utilize "break" in a few different positions (foolish of me), only to find that it terminates my program completely when it is reached.
I'm still a programming green-horn, so please bear with me. I know that my code isn't the most polished thing around and that there are a multitude of ways to improve it, but what I want is full functionality before I begin improving. If you wish to see the classes pertaining to reading, searching and writing please let me know.
Put Scanner iChoice = ... on top
Put everything between that and iChoice.close(); into an infinite loop
Only the scanner init and scanner close method will be outside this loop
String userChoice = ... needs to be inside the loop as well
A proper implementation would also wrap the loop in a try block and close the scanner in finally. Also the logic to perform inside the while loop based on user input might be a candidate for a separate method, to keep the try block easy to comprehend.

How would I go about, using the scanner class, taking in one character and then continuing to display the next random character for the user to enter?

My intentions are to show a letter and have the user type the letter, while after they have hit the corresponding key (whether it's right or wrong) it is to then display the next key. I can only make this happen, at the moment, after pressing the key and then pressing the enter key following so that it finishes the scanner.next() method. Any way that I could automate the enter key so that I could make it scan in the character letter and then automatically continue to the next randomly generated character? Let me know if there needs to be clarification on this.
//some initialized code here
for(int i = 0; i < 5; i++)
{
int letterToDisplay = rand.nextInt(26)
System.out.printf("%s\r\n", letters[letterToDispaly]);
**String inputLetter = scanner.next();**
if(intputLetter.exquals(letters[letterToDisplay]))
{
letterCounter(letterToDisplay);
}
}
//some methods etc. here
Thanks,
Kyle P.
There is no portable way to read user input from a console character-by-character using the standard API; for example the Unix terminal is by default line-buffered which means that the OS does not transfer characters into the application's buffer until the user hits enter. You can't do it even from standard C.
You need to run code specific to the OS and terminal to achieve this, ideally wrapped in a library, like the ones discussed here: What's a good Java, curses-like, library for terminal applications?
A better option is using a graphical user interface. It's not the 1970s anymore ;)

Categories