Java Waiting for Enter Key Solution not Working - java

So I've tried to implement a solution for waiting on user to press enter to continue found here: Java Console Prompt for ENTER input before moving on
However, when I try to use either of the solutions proposed I get the following errors:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at printLine.promptEnterKey(printLine.java:153)
at printLine.main(printLine.java:144)
and
java.io.IOException: Stream closed
at java.base/java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:176)
at java.base/java.io.BufferedInputStream.read(BufferedInputStream.java:342)
at java.base/java.io.FilterInputStream.read(FilterInputStream.java:107)
at printLine.promptEnterKey(printLine.java:155)
at printLine.main(printLine.java:146)
I made a test program before to make sure this would work as expected and it worked fine for me:
// import scanner for user-input
import java.util.Scanner;
public class test{
public static void promptEnterKey(){
Scanner scanner = new Scanner(System.in);
scanner.nextLine();
}
public static void main(String[] args){
promptEnterKey();
}
}
Here's my code, I am working on a program that will read the current line, print it and then wait for the user to hit enter before proceeding:
// import System.out
import static java.lang.System.out;
// import scanner for user-input
import java.util.Scanner;
// import File class
import java.io.File;
// import FileNotFoundException
import java.io.FileNotFoundException;
// delete if ioexception not used
import java.io.IOException;
/* this is the main public class */
public class printLine {
/* this method is used to execute the application */
public static void main(String[] args){
// create scanner for user input
Scanner userInput = new Scanner(System.in);
// user input for file
out.println("This program will print the text file line by line, waiting for the user to hit the enter key");
out.println("Please specify the file to print line by line: ");
String textFile = userInput.nextLine();
userInput.close();
// try to open file
try{
// load the file
File text = new File(textFile);
// for reading the file
Scanner textReader = new Scanner(text);
// while there is another token...
while (textReader.hasNextLine()){
String curLine = textReader.nextLine();
out.println(curLine);
promptEnterKey();
}// end while
// close reader
textReader.close();
}// end try
// catch FileNotFoundException error
catch (FileNotFoundException e){
out.println("File not found.");
e.printStackTrace();
}// end catch
}// end main
/* This method is for waiting for the user to press the Enter key.
this was taken from https://stackoverflow.com/questions/26184409/java-console-prompt-for-enter-input-before-moving-on */
public static void promptEnterKey(){
Scanner scanner = new Scanner(System.in);
scanner.nextLine();
}
}// end class
Here's the sample text excerpt that I am trying to use it on:
There was nothing so VERY remarkable in that; nor did Alice
think it so VERY much out of the way to hear the Rabbit say to
itself, `Oh dear! Oh dear! I shall be late!' (when she thought
it over afterwards, it occurred to her that she ought to have
wondered at this, but at the time it all seemed quite natural);
but when the Rabbit actually TOOK A WATCH OUT OF ITS WAISTCOAT-
POCKET, and looked at it, and then hurried on, Alice started to
her feet, for it flashed across her mind that she had never
before seen a rabbit with either a waistcoat-pocket, or a watch to
take out of it, and burning with curiosity, she ran across the
field after it, and fortunately was just in time to see it pop
down a large rabbit-hole under the hedge.
In another moment down went Alice after it, never once
considering how in the world she was to get out again.
The rabbit-hole went straight on like a tunnel for some way,
and then dipped suddenly down, so suddenly that Alice had not a
moment to think about stopping herself before she found herself
falling down a very deep well.
Either the well was very deep, or she fell very slowly, for she
had plenty of time as she went down to look about her and to
wonder what was going to happen next. First, she tried to look
down and make out what she was coming to, but it was too dark to
see anything; then she looked at the sides of the well, and
noticed that they were filled with cupboards and book-shelves;
here and there she saw maps and pictures hung upon pegs. She
took down a jar from one of the shelves as she passed; it was
labelled `ORANGE MARMALADE', but to her great disappointment it
was empty: she did not like to drop the jar for fear of killing
somebody, so managed to put it into one of the cupboards as she
fell past it.
Any insight as to what I'm doing wrong is appreciated.
Thanks!
JT

you are closing the userInput (System.in) immediately after reading the file name userInput.close();
move that line to the end of your code
Scanner.close will also close it's underlying readable if it implements Closable interface, in your case that is System.in input stream:
https://www.tutorialspoint.com/java/util/scanner_close.htm

Related

Java add new line after a sentence ( why double new line to solve it)?

So while I was trying to do some exercise about IOFile, i tripped in an issue about writing string on a txt file, specifically in writing a new line(\n) after every sentence in a new file.
This is my code:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
File Lyrics = new File("Lyrics.txt");
File output = new File ("output.txt");
try {
Scanner myReader = new Scanner (Lyrics);
try {
FileWriter FBI = new FileWriter(output);
while (myReader.hasNextLine()) {
FBI.write(myReader.nextLine());
FBI.write("\n");
}
FBI.close();
}catch (IOException e) {}
myReader.close();
}catch (FileNotFoundException e) {}
}
}
Lyrics.txt:
I could never find the right way to tell you
Have you noticed I've been gone
Cause I left behind the home that you made me
But I will carry it along
Output:
I could never find the right way to tell you
Have you noticed I've been gone
Cause I left behind the home that you made me
But I will carry it along
***invisible new line here
Output of requested exercise:
I could never find the right way to tell you
Have you noticed I've been gone
Cause I left behind the home that you made me
But I will carry it along
***invisible new line here
After trying adding new line of code and trying to figure out what is going wrong, I simply fixed changing the line of code about adding a new line in
FBI.write("\n\n");
But i'm stil confused why I had to add a double new line (\n\n) to write sentences followed by new line...
\n means new-line.
So if my text is
FooBar\nHello World
i would receive
FooBar
Hello World
Since \n (new-line) made our HelloWorld move to a new line everything is correct.
But you want two new lines (current one + one blank line) instead of one, you have to use \n\n.
Input
FooBar\n\nHello World
Output
FooBar
Hello World
A \n newline character starts a new line immediately under the previous line with no gap. If you want a blank line between sentences you need to add a second \n to create a gap.

hasNextLine() always returning true within While Loop

This question is linked to a previous question I asked regarding the same program, which can be viewed here:
Writing to a file code causing an endless loop
I have fixed the problem above and rewritten the function as a while loop rather than do while, but now I have the opposite problem that nothing is being written to the file. I've inserting a print statement to tell me the status of hasNextLine, and it is always returning as true even when a blank line has been entered, which is when I want the writer to terminate.
Here is the updated code:
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.PrintWriter;;
public class Lab_Week8_WriteAStory {
public static void main(String[] args) throws FileNotFoundException {
Scanner whatToWrite = new Scanner (System.in);
PrintWriter writing = new PrintWriter ("Read and Write Files/output.txt");
while (whatToWrite.hasNextLine()){
String writeToFile = whatToWrite.nextLine();
writing.println(writeToFile);
System.out.println (whatToWrite.hasNextLine());
}
writing.close();
whatToWrite.close();
}
}
Check the documentation for Scanner.hasNextLine():
Returns true if there is another line in the input of this scanner. This method may block while waiting for input. The scanner does not advance past any input.
This is what's happening. Since you are using System.in as input source, the method is waiting for your input and once you provide it, it returns true and proceed to the next line and the process repeats itself.

Why can I not let my program run my method over and over (while loop)?

This is a diary program which allows you to write something in your diary (obviously). After typing enter and pressing enter, the page closes and its gonna be safed in a list. My problem is that it only runs once when I have Pages(); in the main method, so I tried this loop. It doesnt work for me and i dont know why. Need some help
import java.util.ArrayList;
import java.util.Scanner;
public class NotizbuchKlasse{
public static void Pages() {
System.out.println("day 1 : Write something in your diary.");
System.out.println("Write enter if you are done writing.");
ArrayList<String> List = new ArrayList<String>();
String ListInList;
Scanner write = new Scanner(System.in);
do {
ListInList = write.next();
List.add(ListInList);
} while (! ListInList.equals("enter"));
List.remove(List.size()-1);
write.close();
System.out.println("This is now your page. Your page is gonna be created after writing something new.");
System.out.println(List);
}
public static void main(String[]Args){
boolean run = true;
do{
Pages();
} while(run);
}
}
Error:
This is now your page. Your page is gonna be created after writing something
new.
Exception in thread "main" [hello]
day 1 : Write something in your diary.
Write enter if you are done writing.
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at NotizbuchKlasse.Pages(NotizbuchKlasse.java:12)
at NotizbuchKlasse.main(NotizbuchKlasse.java:24)
You need to check whether there is something to read before you read it. You're not currently, and that's why you're getting a NoSuchElementException.
You do this via Scanner's has* methods.
For example:
ArrayList<String> List = new ArrayList<String>();
Scanner write = new Scanner(System.in);
while (write.hasNextLine()) {
String ListInList = write.nextLine();
if (ListInList.equals("enter")) break;
List.add(ListInList);
}
// No need to remove the last item from the list.
But also, I notice that you have a loop in your main method, where you call Pages() in that loop. If you close write, you also close System.in; once a stream is closed, you can't re-open it. So if you try to read things from System.in the next time you call Pages(), the stream is already closed, so there's nothing to read.
Simply don't call write.close(). You shouldn't close streams that you didn't open in general; and you didn't open System.in (the JVM did when it started up), so don't close it.
You want to be using a while loop like this:
while (write.hasNextLine()) {
ListInList = write.nextLine();
if (doneWriting(ListInList)) { // Check for use of enter.
break; // Exit the while loop when enter is found.
}
List.add(ListInList); // No enter found. Add input to diary entry.
}
where doneWriting() is a method (that you write!) which checks to see if the user has typed enter.
Here is the documentation for the next() method of Scanner. If you read it, you will see that it throws the exception you are getting when it runs out of tokens.
If you want a little bit more a casual explanation here is a question that was asked previously about next() versus nextLine().

Print output until key pressed

This seems like a simple problem, but I can't seem to solve it. I need to print output (from a variable) to the console, until the user presses any key. The printing is done in a while loop as such:
int i;
while((i=input.read())!=-1){
System.out.print((char)i);
}
input.close();
The problem is that the input stream never reaches it's end, only waits for more characters to come in, thus blocking any more code from executing. It will be quite obvious to the user when to stop the output, so I am fine with giving that responsibility to the user. It doesn't matter how the user tells the application to stop, as long as it is quick, (eg pressing space, enter, or any other specific key is fine).
Thanks in advance,
vikarjramun
The first solution I came up with was threading the console input. The thread updates a variable accessable by the printing code so you can check it before each print statement.
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicBoolean;
public class RunUntilKeyPressed {
static AtomicBoolean hasUserPressedKey = new AtomicBoolean(false);
public static void main(String[] args) {
Thread t = new Thread(() -> {
Scanner scan = new Scanner(System.in);
System.out.println(scan.next());
hasUserPressedKey.set(true);
scan.close();
});
t.start();
while(!hasUserPressedKey.get()) {
System.out.println(hasUserPressedKey);
}
}
}
This code will run until the user presses Any Key (except space) and Enter as that is when the scan.next() method gets input.

How do streams work when code is executed step by step?

For example, in java, to read input from the console you would write something like this:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ReadConsoleSystem {
public static void main(String[] args) {
System.out.println("Enter something here : ");
try{
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
String s = bufferRead.readLine();
System.out.println(s);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
So in the line String s = bufferRead.readLine(), the code just waits for the input to come in and then goes to the next step, but what if you want to look at a continuous stream of strings trying to parse out pieces of it, for example, reading a stream of Twitter statuses and only saving the ones that have the word "Obama" in it or something?
I don't understand how the code could be executing line-by-line, while handling input from the stream, and then suddenly detecting when input is given and saving it.
bufferRead.readLine(); doesn't return back to the calling code, until the user presses the return key.
That code write there is only set to read in one line of input, from the system's input (that is, the console). It's setup so that when you do readLine, it will read a line from the input. You have to type in something ("Hello there") and hit enter, and it will take that, and put it in String s. If you want to parse stuff out, do it manually afterwords
if(s.contains("Obama")) {
//blah
}
The console is line buffered. This means an entire line comes as once to the Java process so it doesn't see you writing characters or hitting back space to delete them etc.
I suspect you don't need to see how it does this. Perhaps you could describe what problem you are trying to solve?

Categories