【问题标题】:Failing to convert String to int in this program [duplicate]无法在此程序中将 String 转换为 int [重复]
【发布时间】:2019-09-26 15:56:00
【问题描述】:

在第 8 行将字符串转换为 int 时出现错误。

整数 parseInt 方法似乎没有发挥作用。

我尝试使用其他方法来转换字符串,但没有任何效果,这导致我在我正在做的这个编码挑战中失败。我已经剪切了其余的代码,因为我的逻辑中的错误就在这些行中。

错误信息显示



     java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
       at java.lang.Integer.parseInt(Integer.java:583)
       at java.lang.Integer.parseInt(Integer.java:615)
    at Solution.reverseNum(Solution.java:35)
        at Solution.main(Solution.java:8)


    public class Solution {
        public static void main(String args[] ) throws Exception {
            String sc = "1234567890123456";
            int noCases = 1;
            for(int i=0; i<noCases; i++){
                int rev = reverseNum(sc); 
            } // for each credit card number
        }

        public static int reverseNum(String inp){ // helper function
            int in =Integer.parseInt(inp); 
            int res  = 0;
            for(int i = in; i !=0; i/=10){
                res = res *10 + i%10;
            }
            return res;
        }
    }

【问题讨论】:

  • 你为什么要把你的String转换成一个数字来反转它?为什么不直接使用StringBuilder#reverse()
  • 哇,谢谢 azurefrog 直到现在才知道这种方法!

标签: java string type-conversion


【解决方案1】:

1234567890123456 太大而不能成为 int。在这里,用逗号看一下:1,234,567,890,123,456。这是一千万亿。

可能的最大整数是 2,147,483,647。尝试更小的数字或Long.parseLong()

【讨论】:

  • 谢谢这解决了我的问题
猜你喜欢
  • 2017-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-15
相关资源
最近更新 更多