問題描述
所以,在 Java 中,您知道如何像這樣聲明整數:
So, In Java, you know how you can declare integers like this:
int hex = 0x00ff00;
我認為您應該能夠逆轉該過程.我有這個代碼:
I thought that you should be able to reverse that process. I have this code:
Integer.valueOf(primary.getFullHex());
其中 primary 是自定義 Color 類的對象.它的構造函數接受一個整數表示不透明度(0-99)和一個十六進制字符串(例如 00ff00
).
where primary is an object of a custom Color class. It's constructor takes an Integer for opacity (0-99) and a hex String (e.g. 00ff00
).
這是 getFullHex
方法:
public String getFullHex() {
return ("0x" + hex);
}
當我調用此方法時,它會給出我的 NumberFormatException
:
When I call this method it gives my this NumberFormatException
:
java.lang.NumberFormatException: For input string: "0xff0000"
我不明白發生了什么.誰能解釋一下?
I can't understand what's going on. Can someone please explain?
推薦答案
這會有幫助嗎?
Integer.parseInt("00ff00", 16)
16
表示您應該將字符串解釋為基于 16 的(十六進制).使用 2
可以解析二進制數,8
代表八進制.10
是默認值,解析十進制數.
16
means that you should interpret the string as 16-based (hexadecimal). By using 2
you can parse binary number, 8
stands for octal. 10
is default and parses decimal numbers.
在您的情況下, Integer.parseInt(primary.getFullHex(), 16)
將不起作用,因為 0x
前綴由 getFullHex()代碼> - 擺脫,你會沒事的.
In your case Integer.parseInt(primary.getFullHex(), 16)
won't work due to 0x
prefix prepended by getFullHex()
- get rid of and you'll be fine.
這篇關于將十六進制字符串解析為整數會引發 NumberFormatException?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!