PDA

View Full Version : Help with using the scanner class (java)




showtime
Jun 4, 2009, 12:57 AM
How can I get a scanner object to get new line characters as well?

The text file is something like:

Hello world!

How are you?


while(myScanner.hasNext()){
System.out.println(myScanner.nextLine());
}

when I run this code it'll print out:

Hello World!How are you?



plinden
Jun 4, 2009, 01:10 AM
Scanner.nextLine cannot not read any newlines in your file, and System.out.println cannot not print out a new line. So your text file cannot have new lines in there and your Scanner must be loading it all as one line.

Your lines must be separated by some other character that looks like newline to your editor but not to Java.

showtime
Jun 4, 2009, 01:22 AM
Thanks for the reply. I actually tried shortening the code down for the general idea but I guess that wasn't a good idea.

Here's the actual code I'm using

PrintWriter pw = null;
try {
Scanner scan = new Scanner(textfile);

pw = new PrintWriter(savefile);

while(scan.hasNext()){
pw.print(scan.nextLine());
}
}
finally {
pw.close();
}

Dale Cooper
Jun 4, 2009, 01:26 AM
while(scan.hasNext()){
pw.print(scan.nextLine() + "\n");
}

showtime
Jun 4, 2009, 01:30 AM
while(scan.hasNext()){
pw.print(scan.nextLine() + "\n");
}


wouldn't that just be forcing it to print out a new line even if it wasn't there?

for example if my text document document read


Hello


World




it would output?

Hello
World

plinden
Jun 4, 2009, 09:07 AM
It's your PrintWriter.print - look at System.out.println. "println" means "print and add a new line". PrintWriter.print (or System.out.print) doesn't add a new line. So Dale Cooper is almost right, but use pw.println instead to get the same effect. Doing that, your output file will be exactly the same as the input.

I realise I may have been misleading before ... Scanner (or any other Java reader class) just reads up to the end of line. It never includes the new line itself. But that's what I meant by it "cannot not read a newline" ... ie it doesn't ignore new lines.