-4

I have a simple program I am supposed to write. In three methods I need to read in integers, reverse them, and determine if they are palindromes or not. For some reason the numbers always come back as not palindromes even when they obviously are.

This is my code:

import java.io.*;
import java.util.*;
import java.lang.*;
public class main
{

public static boolean isPal;
public static void main(String[] args)
throws FileNotFoundException, IOException
{
    int num;
    int ctr = 0;
    Scanner input = new Scanner(new File("data4.txt"));
    num = input.nextInt();

    while(num != -999)
    {            
        ctr++;
        reverse(num);
        isPalindrome(isPal, num);
        if(isPal == true)
        {
            System.out.println (num + " is a palindrome");
        }
        else
        {
            System.out.println(num + " is not a palindrome");
        }
        num = input.nextInt();
    }        
    System.out.println(ctr + " numbers were processed.");
    System.out.println("End of Program");
}

public static int reverse(int num)
{
    int dig;
    int rnum = 0;
    while(num != 0)
    {
        dig = num % 10;
        num = num / 10;
        rnum = rnum * 10 + dig;
    }
    return rnum;        
}

public static boolean isPalindrome(boolean isPal,int num)
{
    if(num == rnum)
    {
        isPal = true;
    }
    else
    {
       isPal = false; 
    }
    return isPal;
}    
}

and the inputs are

3579 6336 5115 -999

DondonPa
  • 3
  • 2
  • `isPalindrome(isPal, num);` Do something with this... it's not C. – Ryan J Oct 16 '14 at 01:02
  • amongst the many problems you are passing a primitive `boolean` into a method and probably expecting its value to be changed outside the method, it won't be, see the dupe I selected for this. then see Ryan's comment and read about `shadow variables` and `variable scope`. –  Oct 16 '14 at 01:13

1 Answers1

0

You have two variables named rnum, one member of your class, and a different one local in your reverse() function. Fix that.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285