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;
}
}
}
To read a line from a file you should use the nextLine() methond rather than the next() method.
The difference between the two is
While
So you'll have to change your while statement to include nextLine() so it would look like this.
The above code segment reads input from file line by line, if it is not clear, please see this for complete program code
You need to do the following changes
change
to
inputScanner.next() will read the next token
inputScanner.nextLine() will read a single line.