尝试Integer.parseInt时,java.lang.NumberFormatException是一个大字符串

时间:2017-05-10 22:48:02

标签: java

我对java完全陌生(我的第二个学期是cs,但我的第一个学期是java)而且我已经解决了一些关于代码的问题,我遇到了一个希望我与大字符串进行比较的问题并打印">" ,"<" ," ="取决于结果,它适用于大多数情况,除非我输入这样一个巨大的字符串 " 1460175633701201615285047975806206470993708143873675499262156511814213451040881275819636625899967479"

我得到的错误是:

export default class Square extends React.Component{
  handleClick = e => {
      if ( typeof this.props.onTurnChange === 'function'){
          this.props.onChange();
      }
  };
  render(){
    return <div className='Square' onClick={this.handleTurnChange}>
      <img src={this.props.turn}></img>
    </div>
  }
}

这是我的代码:

Exception in thread "main" java.lang.NumberFormatException: For input string: "1460175633701201615285047975806206470993708143873675499262156511814213451040881275819636625899967479"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Qs.Compare.main(Compare.java:13)

我第一次尝试使用编写器,但我想知道我可以使用System.out.print来解决这个问题吗? (问题已经指示这是不可取的)对不起,我知道这是一个非常愚蠢的问题,但我是新的x.x提前谢谢^ _ ^

2 个答案:

答案 0 :(得分:0)

您的输入比Integer的长度大。在使用之前,您必须找出每种数据类型的长度。请参阅data type

答案 1 :(得分:0)

它提供NumberFormatException例外的原因是因为您尝试存储到long类型的数字太大了。另请注意,您使用的是Integer.parseInt而不是Long.parseLong(这在某种程度上会增加NumberFormatException的原因)。除了那个小错误之外,如果您尝试解析String,即使您使用Long.parseLong,它也会再次抛出相同的异常。

您可以使用BigInteger完成任务:

BigInteger n = new BigInteger(bf.readLine());
BigInteger m = new BigInteger(bf.readLine());

if (n.compareTo(m) < 0) {
     // do something
}else if(n.compareTo(m) > 0){
     // do something
}else{
    // do something
}