Search code examples
javapalindromenumberformatexception

How to solve this java.lang.NumberFormatException in palindrome?


I dont know why it won't work... I've tried changing it from int to long... The last input 46894 causes a problem... Help me please.
Here is my code:

import java.util.*;

public class palimdrone
{
   public static void main(String[] args)
   {
      Scanner scan = new Scanner(System.in);
      int[] number = new int[12];

      int input = scan.nextInt();

      for(int x=0;x<input;x++)
      {  
         number[x] = scan.nextInt();
      }

      for(int a=0;a<input;a++)
      {
         long tot =0,sumA=0,sumB=0,attempt=0;
         sumA = number[a];sumB=reverse(number[a]);
         boolean palin=false;

         if(sumA==sumB)
         {
            palin = true;
            attempt++;
         }
         else
         {
            while(attempt!=10)
            {
               attempt++;               
               tot = sumA+sumB;
               if(tot == reverse(tot))
               {
                  palin=true;  
                  break;
               }

               sumA=tot;
               sumB=reverse(tot);    
            }
         }

         if(palin==true)
            System.out.println(tot+" is Palindrome ; Attempt: "+attempt);
         else
            System.out.println(tot+"; None");
      }
   }

   public static long reverse(long num)
   {
      String tnum=""+num;
      String reverse="";
      for(int x=tnum.length()-1;x>=0;x--)
      {
         reverse = reverse+tnum.charAt(x);
      }

      num = Integer.parseInt(reverse);
      return num;
   }

}

Here's the input

87<br>
196<br>
1689<br>
46785<br>
46894 <-- Error Here<br><br>

Here's the output

4884 is Palindrome ; Attempt: 4<br>
18211171; None<br>
56265 is Palindrome ; Attempt: 4<br>
1552551 is Palindrome ; Attempt: 3<br>
Exception in thread "main" java.lang.NumberFormatException: For input string: "2284457131"<br>
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)<br>
at java.lang.Integer.parseInt(Integer.java:583)<br>
at java.lang.Integer.parseInt(Integer.java:615)<br>
at palimdrone.reverse(palimdrone.java:61)<br>
at palimdrone.main(palimdrone.java:34)<br>

Solution

  • 2284457131 is greater than Integer.MAX_VALUE. Try using Long.parseLong(reverse) instead of Integer.parseInt(reverse).