How to determine the end of a line with a Scanner?

Samuel French picture Samuel French · Feb 9, 2012 · Viewed 18.7k times · Source

I have a scanner in my program that reads in parts of the file and formats them for HTML. When I am reading my file, I need to know how to make the scanner know that it is at the end of a line and start writing to the next line.

Here is the relevant part of my code, let me know if I left anything out :

//scanner object to read the input file
Scanner sc = new Scanner(file);

//filewriter object for writing to the output file
FileWriter fWrite = new FileWriter(outFile);

//Reads in the input file 1 word at a time and decides how to
////add it to the output file
while (sc.hasNext() == true)
{
    String tempString = sc.next();
    if (colorMap.containsKey(tempString) == true)
    {
        String word = tempString;
        String color = colorMap.get(word);
        String codeOut = colorize(word, color);
        fWrite.write(codeOut + " ");
    }
    else
    {
        fWrite.write(tempString + " ");
    }
}

//closes the files
reader.close();
fWrite.close();
sc.close();

I found out about sc.nextLine(), but I still don't know how to determine when I am at the end of a line.

Answer

Jon picture Jon · Oct 5, 2012

If you want to use only Scanner, you need to create a temp string instantiate it to nextLine() of the grid of data (so it returns only the line it skipped) and a new Scanner object scanning the temp string. This way you're only using that line and hasNext() won't return a false positive (It isn't really a false positive because that's what it was meant to do, but in your situation it would technically be). You just keep nextLine()ing the first scanner and changing the temp string and the second scanner to scan each new line etc.