Reading File by line instead of word by word

风格不统一 提交于 2019-12-12 12:03:31

问题


I'm trying to write some code that scans for palindromes in an input file, but it gets strings from each word instead of each line. An example would be racecar would show up as racecar= palindrome or too hot to hoot = palindrome but instead it will go too= not a palindrome, hot= not a palindrome etc.

Here is what I am doing to read the file currently

File inputFile = new File( "c:/temp/palindromes.txt" );
Scanner inputScanner = new Scanner( inputFile );
while (inputScanner.hasNext())
{
    dirtyString = inputScanner.next();

    String cleanString = dirtyString.replaceAll("[^a-zA-Z]+", "");

    int length  = cleanString.length();
    int i, begin, end, middle;

    begin  = 0;
    end    = length - 1;
    middle = (begin + end)/2;

    for (i = begin; i <= middle; i++) {
        if (cleanString.charAt(begin) == cleanString.charAt(end)) {
            begin++;
            end--;
        }
        else {
            break;
        }
    }
}

回答1:


You need to do the following changes

change

while (inputScanner.hasNext()) // This will check the next token.

and 

dirtyString  = inputScanner.next(); // This will read the next token value.

to

while (inputScanner.hasNextLine()) // This will check the next line.

and dirtyString = inputScanner.nextLine(); // This will read the next line value.

inputScanner.next() will read the next token

inputScanner.nextLine() will read a single line.




回答2:


To read a line from a file you should use the nextLine() methond rather than the next() method.

The difference between the two is

nextLine() - Advances this scanner past the current line and returns the input that was skipped.

While

next() - Finds and returns the next complete token from this scanner.

So you'll have to change your while statement to include nextLine() so it would look like this.

while (inputScanner.hasNextLine()) and dirtyString = inputScanner.nextLine();



回答3:


FileReader f = new FileReader(file);
BufferedReader bufferReader = new BufferedReader(f);
String line;
//Read file line by line and print on the console
while ((line = bufferReader.readLine()) != null)   {
        System.out.println(line);
}

The above code segment reads input from file line by line, if it is not clear, please see this for complete program code



来源:https://stackoverflow.com/questions/20318872/reading-file-by-line-instead-of-word-by-word

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!