Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

why is this stuck in an infinte loop...

what is wrong with my program, it is supposed to read from a txt file and decide if it is a palindrome or not and then print the palindrome in a new file. It seems to find the first palindrome but then it just prints the first palindrome forever...

import java.io.*; // for IO-related functions
import java.util.*; // for the scanner class

public class FindPalindromes
{
public static void main (String[] args)
{
String inFileName;
String outFileName;
Scanner scan = new Scanner(System.in);

System.out.print("Enter the filename: ");
inFileName = scan.nextLine();

System.out.print ("Enter the output filename: ");
outFileName = scan.nextLine();

BufferedReader reader = null;

PrintWriter output = null;

try
{
reader = new BufferedReader(new FileReader(inFileName));
}
catch(FileNotFoundException e)
{
System.out.println("File " + inFileName + " not found. Exiting.");
System.exit(0);
}

try
{
output = new PrintWriter(new FileOutputStream(outFileName));
}
catch(FileNotFoundException e)
{
System.out.println("File " + inFileName + " not found. Exiting.");
System.exit(0);
}

try
{
String inputLine;

inputLine = reader.readLine();

while (inputLine != null)
{
boolean isPalindrome = true;

for( int i = 0, j = inputLine.length()-1; i < j; i++, j-- )
if( inputLine.charAt(i) != inputLine.charAt(j) )
isPalindrome = false;

if( isPalindrome )
output.println(inputLine);

}
reader.close();
output.close();
}
catch(IOException e)
{
System.out.println("Error reading from " + inFileName + ". Exiting.");
System.exit(0);
}

}
}
[1813 byte] By [bckck5] at [2007-11-11 8:35:32]
# 1 Re: why is this stuck in an infinte loop...
The value of inputLine is never updated. You load the initial value just before the while loop but never update it. Either insert a line at the end of your while or in the loop condition of the while:

while( (inputLine = reader.readLine()) != null) {
...
}

That construct forces an update and only halts execution if the resulting inputLine is null.
JamesW at 2007-11-11 22:34:54 >