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

Why is this stuck in an infinite 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:33]
# 1 Re: Why is this stuck in an infinite loop...
nevermind im dumb forgot to put
another read line at the end of the while loop

:doh:
bckck5 at 2007-11-11 22:34:58 >
# 2 Re: Why is this stuck in an infinite loop...
by the way: to make your code more readable, store all of your file-io in one try catch statement:
try{
reader = new BufferedReader(new FileReader(inFileName));
output = new PrintWriter(new FileOutputStream(outFileName));
String inputLine;

inputLine = reader.readLine();

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

for( int i = 0, j = inputLine.length()-...
...
}

and use the while loop in this 1337 way:
while( (inputLine = reader.readLine())!=null){
//do something
}
this will read and check the next line.
graviton at 2007-11-11 22:35:52 >