0

I'm writing a java program that will require a long String as input from the user. Most of these Strings are news articles copied and pasted off the internet. The problem I've having is that when the user enters the text, it contains carriage returns that Scanner has trouble processing. I'm using the nextLine() method from the Scanner class and the problem is that the carriage returns mark the end of lines and thus terminate that read from the Scanner. I've tried the following code, too, but that results in an infinite loop. UserInput2 is a Scanner.

while(userInput2.hasNextLine())
       toBeProcessed = toBeProcessed + userInput2.nextLine();

Anyone know how I can skip over the carriage returns? Maybe have the scanner convert them to a '+' or something like that so I don't have this problem.

MByD
  • 135,866
  • 28
  • 264
  • 277
Kurtis
  • 59
  • 1
  • 2
  • 3
  • What do you mean by infinite loop? Are you saying that you are inputting from command line and it won't stop? – zw324 Jul 19 '11 at 19:03
  • Well, not exactly. The scanner doesn't recognize the end of the input text when I use the while loop. – Kurtis Jul 19 '11 at 19:08
  • You can try input the end of input twice, which worked for me when I encountered the same problem. – zw324 Jul 19 '11 at 19:09

4 Answers4

1

First, a note: Instead of concatenating String objects you should look into the StringBuilder class.

Second, you could use useDelimiter to something that will never be in the input string, or a nicer method would be to use the Apache commons IOUtils with the InputStream as in this question rather than using a Scanner, which gives you the benefit of specifying a character encoding.

You can strip '\r' characters with String.replace().

Community
  • 1
  • 1
Martin Foot
  • 3,594
  • 3
  • 28
  • 35
0

So do not use Scanner. Use InputStream directly and convert bytes to strings.

AlexR
  • 114,158
  • 16
  • 130
  • 208
0

No matter what method you are using, you must have some sign of input termination. In the Scanner case, you could uuseDelimiter to set the delimiter of the Scanner to whatever you want.

Also you could take a look here and here.

Community
  • 1
  • 1
zw324
  • 26,764
  • 16
  • 85
  • 118
0

You know that there was a newline there because Scanner has used it to determine the end of the line it retrieved. All you have to do is to reinsert what you know was there:

while(userInput2.hasNextLine())
   toBeProcessed = toBeProcessed + userInput2.nextLine() + "\n";

Martin's comment about using StringBuilder is correct. That would change your code to look like:

while(userInput2.hasNextLine()) {
   toBeProcessedSB = toBeProcessedSB.append(userInput2.nextLine()); 
   toBeProcessedSB = toBeProcessedSB.append("\n"); 
}
toBeProcessed = toBeProcessedSB.toString();
rossum
  • 15,344
  • 1
  • 24
  • 38