如何在palindrome中解决这个java.lang.NumberFormatException?

时间:2014-09-06 10:43:20

标签: java palindrome numberformatexception

我不知道为什么它不起作用...我尝试将其从int更改为long ...最后一个输入46894会导致问题...请帮帮我 这是我的代码:

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;
   }

}

这是输入

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

以下是输出

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>

2 个答案:

答案 0 :(得分:4)

2284457131大于Integer.MAX_VALUE。尝试使用Long.parseLong(reverse)代替Integer.parseInt(reverse)

答案 1 :(得分:0)

将输入解析为String而不是数字会更好。所以你永远不必担心溢出。

static boolean isPalindrome(String str) {
    StringBuilder strBuilder = new StringBuilder(str);
    strBuilder = strBuilder.reverse();

    return str.equals(strBuilder.toString());
}

将输入作为String或将整数转换为字符串

    Scanner scan = new Scanner(System.in);
    String input = scan.next();
    System.out.println(isPalindrome(input));