'long' 类型的数字在 java 中打印时更改其值
number of type 'long' changes its value when printed in java
我解析了JSON数据,有本书id,是一个很大的数字:
"Books":[{"ID":88401542,"Title":"Building and Testing with
Gradle","SubTitle":"Understanding Next-Generation
Builds","Description":"Build and test software written in Java and
many other languages with Gradle, the open source project automation
tool that's getting a lot of attention. This concise introduction
provides numerous code examples to help you explore Gradle, both as a
b
..."},{"ID":2676913857...}
long book_id = 0 ;
try {
book_id = jsonBook.getInt(BOOK_ID);
Log.v(LOG_TAG, "book id: " + );
它给我打印了一些愚蠢的负数:
book id: -1814548740
这是什么原因?会不会是因为我没有铸造就打印了?
我的日志语句应该是:
Log.v("book id: " + new Long (book_id)) ;
或
Log.v("book id: " + new Long (book_id.toString())) ;
或
Log.v("book id: " + new String ( new Long(book_id))) ;
可能这个值超过了Integer.MAX_VALUE
。最好使用 BigInteger
:
BigInteger book_id = BigInteger(jsonBook.getText(BOOK_ID));
我不确定 getText()
是否正确,但我的想法是获取值作为 String
。
我觉得你的问题在于:
book_id = jsonBook.getInt(BOOK_ID);
如果 getInt(BOOK_ID)
returns 溢出 int
类型的数字,那么您不应期望它能正常工作。 (我猜int
是因为方法名)。
您可以检查 JSON API 是否有 getLong
方法,或者存储为字符串,然后使用 Long.valueOf
、Long.parseLong
等等...
您使用 getInt()
阅读 long
。如果您尝试读取的 long 值大于 int,那么您得到的是正常值。
由于您的 Book_ID 是长整型,您应该使用 getLong
来获取值:
book_id = jsonBook.getLong(BOOK_ID);
我解析了JSON数据,有本书id,是一个很大的数字:
"Books":[{"ID":88401542,"Title":"Building and Testing with Gradle","SubTitle":"Understanding Next-Generation Builds","Description":"Build and test software written in Java and many other languages with Gradle, the open source project automation tool that's getting a lot of attention. This concise introduction provides numerous code examples to help you explore Gradle, both as a b ..."},{"ID":2676913857...}
long book_id = 0 ;
try {
book_id = jsonBook.getInt(BOOK_ID);
Log.v(LOG_TAG, "book id: " + );
它给我打印了一些愚蠢的负数:
book id: -1814548740
这是什么原因?会不会是因为我没有铸造就打印了? 我的日志语句应该是:
Log.v("book id: " + new Long (book_id)) ;
或
Log.v("book id: " + new Long (book_id.toString())) ;
或
Log.v("book id: " + new String ( new Long(book_id))) ;
可能这个值超过了Integer.MAX_VALUE
。最好使用 BigInteger
:
BigInteger book_id = BigInteger(jsonBook.getText(BOOK_ID));
我不确定 getText()
是否正确,但我的想法是获取值作为 String
。
我觉得你的问题在于:
book_id = jsonBook.getInt(BOOK_ID);
如果 getInt(BOOK_ID)
returns 溢出 int
类型的数字,那么您不应期望它能正常工作。 (我猜int
是因为方法名)。
您可以检查 JSON API 是否有 getLong
方法,或者存储为字符串,然后使用 Long.valueOf
、Long.parseLong
等等...
您使用 getInt()
阅读 long
。如果您尝试读取的 long 值大于 int,那么您得到的是正常值。
由于您的 Book_ID 是长整型,您应该使用 getLong
来获取值:
book_id = jsonBook.getLong(BOOK_ID);