Hi, I'm writing a program that reverses the words of a text file using the LinkedList structure. Unfortunately, I have received the following error:

java.util.Scanner[delimiters=\p{javaWhitespace}+][position=30][match valid=false][need input=false][source closed=true][skipped=false][group separator=\,][decimal separator=\.][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q?\E][infinity string=\Q?\E]

And because of that I'm having difficulty proceeding to the next step. If anyone could point me to the right direction on what to do next, I would greatly appreciate it.

import java.util.*;
import java.io.*;

public class ReverseWords
{
	public static void main(String[] args) throws FileNotFoundException
	{
	   Scanner scan = new Scanner (System.in);
		File f = new File("doriangray.txt");	
		System.out.print("Enter file name: ");
		Scanner input = new Scanner (new File(scan.nextLine()));
		System.out.println();
		System.out.println(input);
	}
		 
	public static LinkedList<String> reverse(LinkedList<String> a)
	{
	   ListIterator<String> order = a.listIterator(a.size());
	   LinkedList<String> reversed = new LinkedList<String>();
	   while (order.hasPrevious())
		{
	      reversed.add(order.previous());
	   }
	   return reversed;
	}
}

The text file contains:

As long as I live, the personality of Dorian Gray will dominate me.

Error? I think what you have posted in the `toString()` representation of the Scanner class. If your code doesn't work, you need to add some debugging statements or even better use an IDE like Eclipse/Netbeans which has debugging support. If you are getting an exception, post the entire stack trace.

Also, in case your motivation for doing System.out.println(input) was to print the contents of the text file, it won't work. You need to loop over the file contents, line by line. Look into the Javadocs of the Scanner class for more details.

Thank you for your response. I modified my code and rid myself of that, however now, no matter what I type in for "the file name", it outputs the contents of the file.

Scanner scan = new Scanner (new File("doriangray.txt"));
Scanner userInput = new Scanner(System.in);
System.out.print("Enter file name: ");
String input = userInput.nextLine();
String output = scan.nextLine();
System.out.println(output);

Edited 5 Years Ago by Amoryethel: n/a

System.out.println(output);

That's why, you get the first line of the input file and print it to the console. You never pass it to your reverse method. Judging by the method signature, you need to take that input line and convert it to a linkedlist first.

A good way to approach this is with String.split().

So basically:

String sentence = "some string of text";
		LinkedList<String> list = new LinkedList<String>();
		
		for (String word : sentence.split(" ")) {
			list.add(word);
		}
This article has been dead for over six months. Start a new discussion instead.