如何将字符串转换为长?

时间:2014-03-07 09:21:46

标签: java string

我在下面添加了代码和错误,请正确更改以下代码。 我得到了NumberFormatException,我该怎么解决呢。

代码:

try{
String balance1 = childNode.getChildText("Balance1");//For input string: "00000162968518794 "
System.out.println(balance1);
long ledgerBalance = Long.valueOf(balance1);
accountSummaryList.setLedgerBalance(ledgerBalance);
System.out.println(ledgerBalance);
}catch(NumberFormatException nfe){
nfe.printStackTrace();
}

输出:

java.lang.NumberFormatException: For input string: "00000162968518794 "
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at java.lang.Long.valueOf(Unknown Source)
at mbank.eai.adaptor.accountsummary.AccountSummaryAdaptor.getAccountSummaryList(AccountSummaryAdaptor.java:68)
at mbank.eai.adaptor.accountsummary.AccountSummaryAdaptor.main(AccountSummaryAdaptor.java:108)
java.lang.NumberFormatException: For input string: "00000162968518794 "
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at java.lang.Long.valueOf(Unknown Source)
at mbank.eai.adaptor.accountsummary.AccountSummaryAdaptor.getAccountSummaryList(AccountSummaryAdaptor.java:68)
at mbank.eai.adaptor.accountsummary.AccountSummaryAdaptor.main(AccountSummaryAdaptor.java:108)

5 个答案:

答案 0 :(得分:6)

您的输入字符串包含尾随空格。先修剪它。

balance1 = balance1.trim();

long ledgerBalance = Long.valueOf(balance1.trim());

答案 1 :(得分:4)

正如错误所示,您最后会有一个额外的空白区域。改变这一行:

String balance1 = childNode.getChildText("Balance1");

对此:

String balance1 = childNode.getChildText("Balance1").trim();

答案 2 :(得分:4)

您的输入字符串未剪裁。异常消息指出您的输入是

"00000162968518794 "

最后有一个额外的空白区域。尝试修剪输入,如:

long ledgerBalance = Long.parseLong(balance1.trim());

答案 3 :(得分:1)

这很简单。

Long.parseLong("786")

答案 4 :(得分:0)

它太简单了。只需看看代码

try{

String balance1 = "0000000162968518794 ";

System.out.println(balance1);

long ledgerBalance = Long.parseLong(balance1.trim());

System.out.println(ledgerBalance);

}
catch(NumberFormatException nfe)
{

    System.out.println("exception");
nfe.printStackTrace();

}