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.
Related
So I'm working on a project that requires me to compare a users input to a list of words in a txt file. I've been trying to compare the the input as a string to the BufferReader, but it hasn't been working. Any suggestions is welcomed
Here's the code for the project
public class Lab5Program1 {
public static void main(String[] args) throws IOException {
File file = new File("fileName");
BufferedReader br = new BufferedReader(new FileReader(file));
/** In order to read a text file that is inside the package, you need to call the actual file and then pass it
* to the BufferedReader. So that it can be used in the file**/
// String[] wordArray = { "hello", "goodbye", "cat", "dog", "red", "green", "sun", "moon" };
String isOrIsNot, inputWord;
// This line asks the user for input by popping out a single window
// with text input
inputWord = JOptionPane.showInputDialog(null, "Enter a word in all lower case:");
// if the inputWord is contained within wordArray return true
if (wordIsThere(inputWord, br))
isOrIsNot = "is"; // set to is if the word is on the list
else
isOrIsNot = "is not"; // set to is not if the word is not on the list
// Output to a JOptionPane window whether the word is on the list or not
JOptionPane.showMessageDialog(null, "The word " + inputWord + " " + isOrIsNot + " on the list.");
} //main
public static boolean wordIsThere(String findMe, BufferedReader bufferedReader) throws IOException {
// for (int i = 0; i < bufferedReader.lines() ; i++){
// if (findMe.equals(theList[i])){
// return true;
// }
// }
while((findMe = bufferedReader.readLine()) != null) {
if (findMe.equals(bufferedReader.readLine())){
return true;
}
}
return false;
} // wordIsThere
}
The error is coming from the function to check if the word exists. Each line being reader from the text file is not being checked with findMe. Made these changes, it works.
public static boolean wordIsThere(String findMe, BufferedReader br) throws IOException {
for (String word = br.readLine() ; word != null; word = br.readLine()) {
if (word.equals(findMe))
return true;
}
return false;
}
In method wordIsThere, parameter findMe is the word you are looking for. However you overwrite the value of the parameter with the line read from the file.
You should declare a separate variable to store the line of text that you read from the file.
public static boolean wordIsThere(String findMe, BufferedReader bufferedReader) throws IOException {
String line = bufferedReader.readLine(); // read first line of file
while(line != null) {
if (findMe.equals(line)){
return true;
}
line = bufferedReader.readLine(); // read next line of file
}
return false;
}
Also note that since you are using JOptionPane to get user input, a separate thread is launched and this thread does not terminate when method main terminates. Hence you should call method exit, of class java.lang.System in the last line of main, in class Lab5Program1. Otherwise, each time you run class Lab5Program1 you will start a new JVM that will not terminate.
For console applications, you can use class java.util.Scanner to get user input.
Scanner stdin = new Scanner(System.in);
System.out.print("Enter a word in all lower case: ");
String inputWord = stdin.nextLine();
Also consider closing files when you have finished with them. In your case it is not necessary since the file is automatically closed when the JVM terminates.
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
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;
}
I have a thread in which data is scanning from standard input stream as:
1. Scanner scan = new Scanner(System.in);
2. while(true)
3. {
4. String str = scan.nextLine();
5. System.out.println(str);
6. }
I want to stop this thread by another thread. I heard it is not good to use Thread.stop(). Using some boolean flag also will not solve it as the pointer (program execution step) will be always at line 4. String str = scan.nextLine();
Is there any way that I can stop the thread?
I think this article will help you, it comes with a code example that solves the problem.
You could either use that code directly, or write a new closable InputStream class, wrapping up the logic described in this article.
public class ConsoleInputReadTask implements Callable<String> {
public String call() throws IOException {
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("ConsoleInputReadTask run() called.");
String input;
do {
System.out.println("Please type something: ");
try {
// wait until we have data to complete a readLine()
while (!br.ready()) {
Thread.sleep(200);
}
input = br.readLine();
} catch (InterruptedException e) {
System.out.println("ConsoleInputReadTask() cancelled");
return null;
}
} while ("".equals(input));
System.out.println("Thank You for providing input!");
return input;
}
}
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(" ");
}