I've been having lots of trouble trying to get either a scanner or a buffered reader to try and detect a blank line. For example if I have a file that contains:
there
cat
dog
(BLANK LINE)
If I do this:
while( scan.hasNextLine() )
{
String line = scan.nextLine();
...
...
}
The scanner doesn't pick up the blank line. I tried to use a buffered reader also but I run into this issue. Is there some way the scanner can just return a "" whenever it finds a blank line like that? Cheers
Your input has as many lines as it has \n characters. Given the input
"there\ncat\ndog\n"
the next-lines will be correctly divided as
"there\n"
"cat\n"
"dog\n"
(In other words, there is no fourth blank line, since it is not terminated by a \n.)
Put differently, after the "dog\n" has been read, the scanner (or buffered reader for that matter) has reached EOF and there's not even an empty line to return. (Note that when the lines are returned, the new-line character is stripped off.)
So, since this is the expected behavior, I don't know what the easiest fix is. I suspect that the best way to solve this is simply to append a \n to the input, so that the loop runs an extra iteration.
Related
I'm helping my sisters with a simple java program and I'm stumped. They've only learned scanner classes to read file contents, so I think they're supposed to use the scanner class. Each line contains letters and potentially a blank space, and we're hoping to store each line in an array. This works fine and dandy until one of the lines contains something like:
abcde f (the blank space after f should be read in as part of the
line).
However, scanner.nextLine() seems to disregard this last blank space. I figured I could set my scanner delimiter to \n like so:
scanner.useDelimiter("\n")
and then use scanner.Next() from there, but this still doesn't seem to work. I've googled around and taken a look at a few stackoverflow questions. This question here seems to suggest this is not easily done with the scanner class: How to read whitespace with scanner.next()
Any ideas? I feel like there's an easy way I'm overlooking.
This is how I'm reading in the lines:
While(scanner.hasNextLine(){
String nextLine = scanner.nextLine();
Using the above example, my string would read abcde f. It will get rid of the empty space at the end.
I've also tried to use hasNext and next.
Pardon my formatting, I'm editing on a phone.
Save your text file as ANSI encoding and try again.
By right scanner.nextLine() will capture everything in the line, including whitespace.
scanner.next() will not capture whitespace as the delimiter is whitespace by default.
So I have to get words from a text file, change them, and put them into a new text file.
The problem I'm having is, lets say the first line of the file is
hello my name is bob
the modified result should be:
ellohay myay amenay isay bobay
but instead, the result ends up being
ellomynameisbobhay
so scanner has .nextLine() but I want to have a method that is .nextWord() or something, so that it will recognize something as a word until it has a space after it. how can I create this?
nextLine() gives you the whole line.
What you should use is just next(), that will give you the next word.
Also see String.split() or StringTokenizer if you wanted to post-process whole lines. It sound s as though in your situation just using the scanner is fine, but I though i'd mention it because I assumed you'd have just used those methods if you knew about them.
I am using BufferedReader as follows,
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
for (int i = 0; i < 4; i++) {
System.out.println(stdin.readLine());
}
And the input given is as follows,
1
2
3
The last input doesn't end with \n or \r, therefore for 3 readLine() will expect input from user unless user presses enter key
Any solution for this using Scanner ?
Actually, I got into this problem while solving , Quora Question Nearby, In their conditions they have mentioned following lines,
Does the last line in the input test case end with a newline? [link]
Nope. No trailing spaces or newlines.
Link for Code, Submitted at above page, test cases are failing
For Test Case Zero, It shows following output ,
Since, expected output is blank, it means my codes still expects \n or \r which is not provided by input
If the input is terminated - which would be the case if standard input is actually being redirected from a file, for example - then it's fine. BufferedReader.readLine will still return the last line from its input, when it detects the end of the underlying data.
Given that this is an automated challenge, I would expect this to be the case - I'd expect it to be run as something like
java Solution < input.txt
So basically, I believe you should be fine.
If you want to get the output without pressing enter,it is impossible.
Because System.in stream doesn't allow you to take input without pressing enter by default.You have to use a third party library like JNI for that.
I am trying to read a CSV file in to my application to read a bunch of data into a table.
Every row is separated by commas and each end of the row has a carriage return. I try using the scanner in java to read the first line with delimiter set to (","), but I can't figure out how to stop the scanner at the end of the first row when it reached the carriage return. This is the code I have so far that scans in everything in the file since it doesn't stop at carriage returns.
Scanner scn = new Scanner(inputStream);
Vector<String> columnTitles = new Vector<String>();
scn.useDelimiter(",");
// Read the first line to get the column names.
while(!scn.hasNextInt())
{
String newStr = scn.next();
columnTitles.add(newStr);
System.out.print(newStr);
}
The idea seems so simple, yet everywhere I look has useless examples that all don't work.
If you're simply trying to populate the columnTitles vector with the first line of the file and then process the rest of the file (or not)
Use a BufferedReader on your file to read the first line into a string
Create a scanner using that string
Populate the vector using the scanner from step 2
Then if you want to process the rest of the file, do what you are doing above but call scn.nextLine() before your while loop to skip the first line of the file
You could use two scanners:
new Scanner(scanner.nextLine());
or a BufferedReader and a scanner
new Scanner(bufferedReader.readLine());
or BufferedReader and split.
bufferedReader.readLine().split(",");
In your case I think the only thing you gain from scanner is the ability to call nextInt() instead of converting the String to an int yourself (which is easy enough to do).
A Carriage Return is a control character in Unicode/ASCII, and can be identified by its hex value just like any other "visible" character. New Line is 0x0A (10), and Carriage Return (they are slightly different things) is 0x0D (13).
I've got some very basic code like
while (scan.hasNextLine())
{
String temp = scan.nextLine();
System.out.println(temp);
}
where scan is a Scanner over a file.
However, on one particular line, which is about 6k chars long, temp cuts out after something like 2470 characters. There's nothing special about when it cuts out; it's in the middle of the word "Australia." If I delete characters from the line, the place where it cuts out changes; e.g. if I delete characters 0-100 in the file then Scanner will get what was previously 100-2570.
I've used Scanner for larger strings before. Any idea what could be going wrong?
At a guess, you may have a rogue character at the cut-off point: look at the file in a hex editor instead of just a text editor. Perhaps there's an embedded null character, or possibly \r in the middle of the string? It seems unlikely to me that Scanner.nextLine() would just chop it arbitrarily.
As another thought, are you 100% sure that it's not all there? Perhaps System.out.println is chopping the string - again due to some "odd" character embedded in it? What happens if you print temp.length()?
EDIT: I'd misinterpreted the bit about what happens if you cut out some characters. Sorry about that. A few other things to check:
If you read the lines with BufferedReader.readLine() instead of Scanner, does it get everything?
Are you specifying the right encoding? I can't see why this would show up in this particular way, but it's something to think about...
If you replace all the characters in the line with "A" (in the file) does that change anything?
If you add an extra line before this line (or remove a line before it) does that change anything?
Failing all of this, I'd just debug into Scanner.nextLine() - one of the nice things about Java is that you can debug into the standard libraries.