【问题标题】:Why I can't convert a String to int?为什么我不能将 String 转换为 int?
【发布时间】:2020-04-22 16:19:50
【问题描述】:

我是 Java 新手。我有问题。 我有一个字符串 currentTime,其当前时间的值如下:“2204201810”。 我想将此字符串转换为整数。 错误是:

原因:java.lang.NumberFormatException:对于输入字符串:“2204201804”

但是不知道为什么Java不能转换!我的意思是字符串只包含数字而不是更多。

这是我的代码:

GregorianCalendar now = new GregorianCalendar();
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);

df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
String currentTime = df.format(now.getTime());

currentTime = currentTime.replace(".", "");
currentTime = currentTime.replace(" ", "");
currentTime = currentTime.replace(":", "");
try {
    int currentTimeInt = Integer.valueOf(currentTime);
} catch (NumberFormatException ex) {
    //Error
}

【问题讨论】:

  • 你查看currentTime的内容了吗?我怀疑它有你期望的内容/格式
  • 打印替换前后的字符串,你可能会跳过一些不能转换为int的字符
  • 我不确定下面的答案是如何工作的。运行此代码 System.out.println(currentTime); 时,输出为 4/22/201042AM,据我所知,它不能转换为 int、long 或 BigInteger。
  • @hooknc,那么您的操作系统中有不同的语言环境设置,它们使用斜线而不是点、逗号或冒号,并且最后还会附加 AM/PM。

标签: java string int


【解决方案1】:

您尝试转换为 int (2204201804) 的值超过了最大整数容量,即 Java 中的 2147483647。尝试改用long。或者甚至可能是BigInteger,这取决于您的需要。

【讨论】:

  • 没问题。你能接受这个答案是正确的吗?
猜你喜欢
  • 2016-06-12
  • 2016-03-07
  • 2013-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-15
  • 1970-01-01
相关资源
最近更新 更多