Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

java - Converting Hexadecimal String to Decimal Integer

I wrote some code to convert my hexadecimal display string to decimal integer. However, when input is something like 100a or 625b( something with letter) I got an error like this:

java.lang.NumberFormatException: For input string: " 100a" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source)

Do you have any idea how can I convert my string with letters to decimal integer?

if(display.getText() != null)
{
    if(display.getText().contains("a") || display.getText().contains("b") || 
       display.getText().contains("c") || display.getText().contains("d") || 
       display.getText().contains("e") ||display.getText().contains("f"))
    {   
        temp1 = Integer.parseInt(display.getText(), 16);
        temp1 = (double) temp1;
    }
    else
    {
        temp1 = Double.parseDouble(String.valueOf(display.getText()));
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It looks like there's an extra space character in your string. You can use trim() to remove leading and trailing whitespaces:

temp1 = Integer.parseInt(display.getText().trim(), 16 );

Or if you think the presence of a space means there's something else wrong, you'll have to look into it yourself, since we don't have the rest of your code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...