0

For a spell checking program that parses a text file dictionary into a quadratic probing hash table, I'm having trouble counting line numbers...

input = new Scanner(userInput);
int counter = 1;
while (input.hasNext())
{
    String x = input.next();
    x = x.replaceAll("[^a-zA-Z\\s]", "").replaceAll("\\s+", " ");
    if (!dictionary.contains(x))
    {
        System.out.println("Mispelled word: " + x + ", on line #: " + counter);
    }
    if (x.contains("\n"))
        counter++;
}

This correctly identifies misspelled words at any location in the file constructed as userInput, but does not produce accurate line numbers.

Since the input text file contains multiple words per line, I used the input.next() method instead of input.nextLine(). I'm trying to use the int counter to count correct line numbers.

The text file containing:

This is a missspelled word test documentt.
How many dogs can fly? It doesn't produce correct linee numbbers.
Do you think this really works?

Produces the output with wrong line numbers:

Mispelled word: missspelled, on line #: 1
Mispelled word: documentt, on line #: 1
Mispelled word: linee, on line #: 1
Mispelled word: numbbers, on line #: 1

My if statement with the counter++ isn't doing the trick.

Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
RRTT93
  • 5
  • 1
  • 4

1 Answers1

0

This should work!

        Scanner inputLine;
        Scanner inputToken;
        try {
            int counter = 1;
            inputLine = new Scanner(new File("a.txt"));
            while(inputLine.hasNextLine()){
                inputToken=new Scanner(inputLine.nextLine());
                while (inputToken.hasNext())
                {
                    String x = inputToken.next();
                    x = x.replaceAll("[^a-zA-Z\\s]", "").replaceAll("\\s+", " ");
                    if (!dictionary.contains(x))
                    {
                        System.out.println("Mispelled word: " + x + ", on line #: " + counter);
                    }
                    if (x.contains("\n"))
                        counter++;
                }
                counter++;
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
Marcelo Ruiz
  • 373
  • 3
  • 14
  • I hadn't thought of using two different Scanner objects on the same file... That does work. Thanks, also thanks to the person that suggested this in comments above. – RRTT93 Apr 04 '15 at 03:48