Press Anykey in Java with BufferedReader - java

How to detect keyboard input when user press anykey and then doSomething/Repeat Method, unless escape button without swing/awt ?
public static void isChecking(String x)throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String anykey = null;
System.out.print("Press Anykey to Continue : ");
anykey = br.readLine();
//if pressanykey
main(null); //call main class
//if escape button
System.out.println("Good Bye ");
System.exit(1);
}
Thanks
MRizq

There's no way to detect KeyPress in java with console I guess. Althought there's a way to do it natively, using JNI. You can get an example with source code from here
Regarding continuous input till you break, you can do it with simple while loop:
while((input = in.readLine()) != null){
System.out.println();
System.out.print("What you typed in: " + input);
}

How about a simple loop:
boolean escapeIsNotPressed = true;
while (escapeIsNotPressed) {
anyKey = br.readLine();
if (anyKey.equals(espaceCharacter)) {
escapeIsNotPressed = false;
} else {
main(null)
}
}
Not sure what is the String representation of the escape character. Try to show it using a System.out.println(anykey) and the introducing it in your code.

Note, the escape button is not a character that will be passed in via System.in. Besides, you are using the readLine method so, if the user types "abc" and then enter, your anyKey variable will contain "abc".
Basically what you need to do is to listen on events on the keyboard. Check out this tutorial http://download.oracle.com/javase/tutorial/uiswing/events/keylistener.html.

try this way
public void keyPressed(KeyEvent e) {
while(!e.keyCode == Keyboard.ESCAPE) {
//do something
}
}

Related

user input errors illegal start of expression and type

I'm writing a simple program where the program asks the user to input some strings and a certain output in generated based on the user's input. But when I run the code the I got some error.Errors I've also tried the scanner import but the same exceptions pop up. And when I moved the imports outside of my main I got 3 different errors again.Errors At this moment I don't need the method to be looped or anything, just want to have it so the program can spit out some output based on user's input. Thanks.
public class Question {
public static void main(String arg[]) {
import java.io.BufferReader;
BufferReader br = new BufferReader(new InputStreamReader(System.in));
String input = br.readLine("who's your daddy?");
if (input = "you're my daddy.") {
System.out.println("correct");
else {
System.out.println("try again");
}
}
}
}
Edit:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Question {
public static void main(String[] args) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String input = in.readLine();
if ("you're my daddy.".equals(input)) {
System.out.println("correct");
} else {
System.out.println("try again");
}
} catch (IOException ex) {
System.out.println("Error reading from System.in");
}
}
}
Another hint for String comparisons:
It is better to put the String constant in the first place of the comparison to avoid NullPointerExceptions.
if ("you're my daddy.".equals(input)) {
// ...
}
And a brief explanation of why == is not correct here:
This checks if two objects are the same (identity). Every time you write "you're my daddy." a new String is created. Therefore the comparison with == would never be true although the content of the String is identical.
Comparisons are achieved with ==, not =. And, in Java, for Strings, you should use the equals() method fot that
input.equals("you're my daddy.")
To compare things, you use ==, not =. That is assignment.
However, input is a string. So you want to use -
if (input.equals("you're my daddy.")) {
Read up about this here - What is the difference between == vs equals() in Java?
In your code..
you can use buffered reader outside of main like this
private static BufferReader br = new BufferReader(new InputStreamReader(System.in));
if (input = "you're my daddy.") { // by using equals method. your code is wrong here
System.out.println("correct");
// not closing curly braces here
public class V
{
public static void main ( String [] args )
{
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your input string: ");
String input = reader.readLine();
System.out.println("Your input is: " + input);
String input1="you're my daddy.";
if (input.equals(input1))
{
System.out.println("correct");
}
else
{
System.out.println("try again");
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
} enter code here

How can i detect that user has pressed enter key (in java) And what, if i want to use enter key in the condition of a loop?

please help me!
M new to java. I want that a specific line of my code must be executed just after the enter button has been pressed. Like: int x= in.nextInt(); then a value is stored in x after pressing enter.
now i want to use such mechanism in a loop.means; perform this statement if Enter button has pressed else do another statement.
if(!Enter key pressed)
{
}
else if(space has been pressed)
{
}
now tell me what kind of code should i write in java?
i don't want to use listeners.
so suggest me what should i do?
Simply read a line of input. If you're reading from user input:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = null;
try {
input = br.readLine();
//this code will be executed after user pressed enter
} catch (IOException e) {
//handle exception
}
Likewise, if you're reading from a file, simply change System.in to your file (opened with a File object):
File file = new File(path);
BufferedReader br = new BufferedReader(new InputStreamReader(new FileReader(file)));
If you want to distinguish between input characters (such as enter or space), read it character by character (instead of complete line) - simply use read() instead of readLine() - and ask what the value of the character is:
char c = (char)br.read();
if (c == ' ') {
// this is a space
} else if (c == '\n') {
// this is a new line (Enter)
}
Notice that '\n' will work for most operating systems, as Linux only uses it to mark a new line and Windows uses '\r\n'. If you want to support iOS as well, you may ask if the character is '\r' (but has no '\n' following it)

Using the standard/output stream as string input/output

I have an assignment stating that "You can assume that input will come from standard input in a stream. You may assume that the markers have access to all standard libraries".
How do I go about reading several lines/inputs and saving all the inputs as one string and then outputting that string from a function?
Currently this is my function, but it's not working properly, at one stage it wasn't reading more than one line and now it doesn't work at all.
public static String readFromStandardIO() {
String returnValue = "";
String newLine = System.getProperty("line.separator");
System.out.println("Reading Strings from console");
// You use System.in to get the Strings entered in console by user
try {
// You need to create BufferedReader which has System.in to get user
// input
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
String userInput;
System.out.println("Enter text...\n");
while (!(reader.readLine() == reader.readLine().trim())) {
userInput = reader.readLine();
returnValue += userInput;
}
System.out.println("You entered : " + returnValue);
return returnValue;
} catch (Exception e) {
}
return null;
}
Thank you for the assistance!
The problem is you're calling reader.readLine() three different times, so you'll end up comparing two completely different strings and then recording yet another one.
Also, it's generally frowned upon to compare strings using == (as comparing Objects with == asks if they are the same actual object (yes, Java's forgiving in that regard with strings, but it's still frowned upon)).
You'll need to do something more akin to:
public static String readFromStandardIO() {
String returnValue = "";
System.out.println("Reading Strings from console");
// You use System.in to get the Strings entered in console by user
try {
// You need to create BufferedReader which has System.in to get user
// input
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String userInput;
System.out.println("Enter text...\n");
while (true) {
userInput = reader.readLine();
System.out.println("Finally got in here");
System.out.println(userInput);
returnValue += userInput;
if (!userInput.equals(userInput.trim())) {
break;
}
}
System.out.println("You entered : " + returnValue);
} catch (Exception e) {
}
return returnValue;
}

Catching System.in events from the terminal

I'm developing an application that has to receive multiple pieces of input from the user's terminal, while elegantly handling invalid input and prompting the user to re-enter it. My firs thought would be to have a while loop whose body will take the input and verify it's validity, setting a flag when it gets valid input. This flag will mark the stage the application is at and will determine what type of input is required next, and will also be used as the terminating condition of the loop.
While functional, this seems rather inelegant and I was wondering if there was a way I could simply write a function that is called whenever the return key is pressed to indicated that there is new input to be parsed. Something along the lines of
public class Interface {
public void receiveInput( final String input ){
// Parse 'input' for validity and forward it to the correct part of the program
}
}
Perhaps this could be achieved by extending some Java class and reimplementing one of it's functions that would normally handle such an event, but that's perhaps my C++ background talking.
I'm not allowed to use any external libraries, other than those requires for building and unit testing.
While reading from the console you can use BufferedReader
BufferedReader br = new BufferedReader( new InputStreamReader( System.in));
and by calling the readLine function, it will handle new line :
String readLine = br.readLine();
You can sure have a class in which there would be a function which reads the information and continue.
Here is the sample code for your reference
public class TestInput {
public String myReader(){
boolean isExit = true;
while (isExit){
System.out.print("$");
BufferedReader br = new BufferedReader( new InputStreamReader( System.in));
try {
String readLine = br.readLine();
if (readLine != null && readLine.trim().length() > 0){
if (readLine.equalsIgnoreCase("showlist")){
System.out.println("List 1");
System.out.println("List 2");
System.out.println("List 3");
} if (readLine.equalsIgnoreCase("shownewlist")){
System.out.println("New List 1");
System.out.println("New List 2");
} if (readLine.equalsIgnoreCase("exit")){
isExit = false;
}
} else {
System.out.println("Please enter proper instrictions");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "Finished";
}
/**
* #param args
*/
public static void main(String[] args) {
System.out.println("Please Enter inputs for the questions asked");
TestInput ti = new TestInput();
String reader = ti.myReader();
System.out.println(reader);
}
Here is the output:
Please Enter inputs for the questions asked
$showlist
List 1
List 2
List 3
$shownewlist
New List 1
New List 2
$exit
Finished
Hope this helps.

Java interactive input EOF

I'm trying to implement a user input interface for a board game. I'm trying to get user input one at a time and then writing it to a file (since I need to save the list of moves made by the user). What I have so far, works well (reading input and writing it to file), however, whenever the user wants to stop inputting, the program just stops working. I.E; when you press ctrl+c, the program just ends.
Here is what I have so far, the fileName variable has been declared outside the main function
public static void main(String[] args) throws IOException {
BufferedReader inputReader = new BufferedReader (new InputStreamReader (System.in));
try {
FileWriter outFile = new FileWriter (fileName);
PrintWriter out = new PrintWriter (outFile);
System.out.print ("Enter move: ");
String line = inputReader.readLine();
while (line != null) {
System.out.print ("Enter move: ");
out.write(inputReader.readLine());
out.write(" ");
}
out.close();
} catch (IOException e) {
System.out.println (e.getMessage());
}
System.out.println ("Reached here");
}
What I'm trying to do is whenever the user wants to stop inputting, I want to get to the print line where it says "Reached here". I want to do this because once outside of the loop, I can read the file and then split the input and maniplate it. I remember whilst programming in C, there used to be while (input != EOF); where whenever the user entered ctrl+d or ctrl+c, it stops whatever it is doing and then moves onto the next line of code.
How can I do this in java?
Many thanks.
If you flush after each write, you should at least get a complete file when the user hits control-c.
As for processing more information after control-c happens, you can do that by using a shutdown hook such as:
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
// do something before quiting
}
});
however, i don't know that you can cancel the termination.
I would choose a more normal character input for the 'no more input' action.
You can catch the Ctrl+C signal using a SignalHandler. Although I wouldn't recommend this as it would make it difficult for the user to exit your application. Instead you could stop input when the user enters nothing, or use a different command signal.
You need to agree with a command indicating that user is done (for example "EOF") and add the following in your while loop:
while (line != null) {
System.out.print ("Enter move: ");
String r = inputReader.readLine();
if ( r != null ) {
if ( "EOF".equals(r) ) break;
}
out.write();
out.write(" ");
}

Categories

Resources