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(" ");
}
Related
I need to do the following exercise:
a) Make a new text file
b) Put the user's input into that text file
c) we must save all user's input while user keeps typing but as soon as user pressing Enter in a new line (When an empty string is sent) the user must get out of the program.
For coding this issue I have write the following codes, but when
I try it by myself so I am stuck at while loop, cant get out when I sending empty string.
So could anyone help with a solution for this issue?
Thanks
I have tried some of the solutions I have found on youtube like making if statement inside the while loop or adding the code that takes the input of the user inside the loop's condition.
So I do not know what to do at the next stage.
I tried to see the console window via the Eclipse output.
import java.io.*;
import java.util.Scanner;
public class lesson {
public static void main(String[] args) throws IOException {
File file = new File("mytext.txt");
if (file.exists() == false) {
file.createNewFile();
}
PrintWriter pw = new PrintWriter(file);
System.out.println("Enter a text here: ");
String str;
while (true) {
Scanner input = new Scanner(System.in);
str = input.next();
pw.println();
if (str.equals(null)) {
break;
}
}
pw.close();
System.out.println("Done");
}
}
The user must get out of the loop when he/she sends an empty string. and the writing to the file must be finished.
First the code, then the explanation...
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Lesson {
public static void main(String[] args) {
File file = new File("mytext.txt");
try (Scanner input = new Scanner(System.in);
PrintWriter pw = new PrintWriter(file)) {
System.out.println("Enter a text here: ");
String str = input.nextLine();
while (str.length() > 0) {
pw.println(str);
pw.flush();
str = input.nextLine();
}
}
catch (IOException xIo) {
xIo.printStackTrace();
}
System.out.println("Done");
}
}
The above code requires at least Java 7 since it uses try-with-resources. Scanner should be closed, just like PrintWriter should be closed. The try-with-resources ensures that they are closed. Note that if file mytext.txt doesn't exist, creating a new PrintWriter will also create the file and if the file already exists, its contents will be removed and replaced with the text that you enter.
After that the prompt is displayed, i.e. Enter a text here, and the user enters a line of text. Method nextLine() will get all the text entered until the user presses Enter. I read your question again and the program should exit when the user presses Enter without typing any text. When the user does this, str is an empty string, i.e. it has zero length. That means I need to assign a value to str before the while loop, hence the first call to method nextLine() before the while loop.
Inside the while loop I write the value entered by the user to the file mytext.txt and then wait for the user to enter another line of text. If the user presses Enter without typing any text, str will have zero length and the while loop will exit.
Written and tested using JDK 12 on Windows 10 using Eclipse for Java Developers, version 2019-03.
To achieve this, we check is length of input is >0:
import java.io.*;
import java.util.Scanner;
public class lesson {
public static void main(String[] args) throws IOException {
File file = new File("mytext.txt");
if (file.exists() == false) {
file.createNewFile();
}
PrintWriter pw = new PrintWriter(file);
System.out.println("Enter a text here: ");
String str;
Scanner input = new Scanner(System.in);
while ((str = input.nextLine()).length() > 0) {
//str = input.next();
pw.println(str);
}
pw.close();
System.out.println("Done");
}
}
I'm currently working on a small chat program.
This is the important part of my server class so far, which starts a thread to listen to client input:
Scanner in = new Scanner(socket.getInputStream());
PrintWriter out = new PrintWriter(socket.getOutputStream());
while (true) {
if ( in .hasNextLine() && clientName == null) {
clientName = in .nextLine();
}
if ( in .hasNextLine()) {
String input = in .nextLine();
out.println(clientName + ": " + input);
out.flush();
}
}
However, this is constantly looping. I want it to wait for the input, and pause the thread until this happens. Is there a built in function for Scanner to wait for a next line, instead of checking if there is one and then returning true of false?
Just remove the hasNextLine call, and nextLine will block.
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)
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.
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
}
}