So as you may be able to tell from my attempt, I'm trying to figure out how I'd make a program which gives the user 5 seconds to enter some lines of text, then the Scanner will count how many lines were entered. I've just started learning Java as my 2nd language, so please try to explain everything as simply as possible :)
I've got two theories as to why it's not working. The first is that nextLine() will return the whole line, regardless of whether it's empty or not meaning rather than NL equaling "", it will actually equal the whole line (ie " "). And my second theory is that I've got no idea what I'm doing and the program flow is all over the place. Anyway, here's my code:
class OrigClass{
public static void main(String args[]){
Scanner ScanObj = new Scanner(System.in);
int Count = 0;
String NL = ScanObj.nextLine();
try{
Thread.sleep(5000);}
catch (InterruptedException e){
e.printStackTrace();
}
while (!NL.equals("")){
Count++;
NL = ScanObj.nextLine();
}
System.out.print("You Entered " + Count + " Lines.");
ScanObj.close();
}
}
Oh, I forgot to mention hasNext() was what I originally tried:
import java.util.Scanner;
class OrigClass{
public static void main(String args[]){
Scanner ScanObj = new Scanner(System.in);
int Count = 0;
try{
Thread.sleep(5000);}
catch (InterruptedException e){
e.printStackTrace();
}
while (ScanObj.hasNext() == true){
Count++;
ScanObj.nextLine();
}
System.out.print("You Entered " + Count + " Lines.");
ScanObj.close();
}
}
Well this solution is not really good. but works.
but the best approach is about running a separated process to count the lines, and you would just remove the
[S2]
comments to achieve it.From the looks of it, this code should work. My only guess is that you are manually entering the input and are forgetting to signal the end of input with
CTRL+D
. However, doing this, you'll get aNoSuchElementException
if you do not useScanObj.hasNext()
.You could also run your code using input redirection.
java OrigClass < data
A better way to do this would be the following:
The difference here is that we save the first
nextLine()
until we're in the while loop. This will give an accurate count of how many lines are in the input.Just don't forget to signal end of input with
CTRL+D
.