integer number too large что значит
«Integer number too large» error message for 600851475143
8 Answers 8
600851475143 cannot be represented as a 32-bit integer (type int ). It can be represented as a 64-bit integer (type long ). long literals in Java end with an «L»: 600851475143L
By default, java interpret all numeral literals as 32-bit integer values. If you want to explicitely specify that this is something bigger then 32-bit integer you should use suffix L for long values.
You need to use a long literal:
The java compiler tries to interpret 600851475143 as a constant value of type int by default. This causes an error since 600851475143 can not be represented with an int.
Since some Fonts make it hard to distinguish «1» and lower case «l» from each other you should always use the upper case «L».
You need 40 bits to represent the integer literal 600851475143. In Java, the maximum integer value is 2^31-1 however (i.e. integers are 32 bit, see http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Integer.html).
At compile time the number «600851475143» is represented in 32-bit integer, try long literal instead at the end of your number to get over from this problem.
Apart from all the other answers, what you can do is :
Not the answer you’re looking for? Browse other questions tagged java integer or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.11.10.40714
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Java «Integer number too large» в расчете добавления даты
Я вынул нерелевантный код для своего вопроса и оставил то, что имеет отношение к моей проблеме. Он утверждает, что целое число слишком велико. Я преобразовал текущее время в миллисекунды и пытаюсь добавить месяц, 2 недели и 1 неделю в миллисекундах, чтобы достичь ‘Date Expired’. Если кто-нибудь знает, как я буду использовать Long вместо int? Я в замешательстве, так как моя дата не делится на целое число?
Он констатирует ошибку в ‘ dateExpired = dateExpired + 2628000000;’.
2 ответа
Я новичок в разработке Windows и довольно смущен. Когда я компилирую этот код с Visual C++ 2010, я получаю ошибку constant too large. почему я получаю эту ошибку и как ее исправить? Спасибо! int _tmain(int argc, _TCHAR* argv[])
Добавьте маркер L после ваших чисел, чтобы превратить их в литералы long :
Вы также столкнетесь с проблемой добавления неправильных типов. Либо измените dateExpired на long (и преобразуйте его в Date позже), либо используйте эту форму:
Просто в стороне, это может помочь вам позже задокументировать, что означают большие цифры:
Вы не можете добавить объект даты в длинный объект
Похожие вопросы:
Внезапно, в последние 2-3 дня я начал получать это исключение Task size too large на GAE. Обратите внимание, что задача тратит всего 4 секунды, и исключение возникает после выполнения. Что означает.
Запуск jjs или ScriptEngine#eval на моем JavaScript ( https://gist.github.com/also/005fd7c200b20f012e10 ) завершается сбоем с этим исключением и больше никаких подробностей: Exception in thread main.
Я работаю над кросс-компиляцией libbtbb в Android, и я получаю тонну предупреждений, которые говорят:: jni/libbtbb/bluetooth_packet.h:67: warning: integer constant is too large for ‘long’ type.
Я новичок в разработке Windows и довольно смущен. Когда я компилирую этот код с Visual C++ 2010, я получаю ошибку constant too large. почему я получаю эту ошибку и как ее исправить? Спасибо! int.
У меня есть парсер, написанный на функциональном языке bigloo scheme, который мне нужно скомпилировать в класс java. Весь парсер записывается как одна функция. К сожалению, это приводит к тому, что.
Я в основном играл с типами данных, чтобы узнать java, и вот что меня смущает. double douVar = 30000000000.323262342134353; int intVar = (int)douVar; // casting System.out.println(intVar); Теперь.
У меня есть отсортированный массив контактов, и каждый объект имеет имя(строка) и номер телефона(длинный). Я использую двоичный метод поиска, который возвращает индекс контакта с тем же номером.
java integer number too large
1. Error:Integer number too large:600851475143 stackoverflow.com
Hi I have written this code: but it will show this error for this line : obj.function(600851475143);
2. why 09 is a too large integer number? stackoverflow.com
3. integer number too large: coderanch.com
4. Integer too large? coderanch.com
5. integer number too large coderanch.com
6. integer number too large coderanch.com
Hi Experts, I was trying a program to convert the miliseconds we get after from date object (Post Jan 1970) to date object again. Here what I was trying and I am getting interger number too large error. I am using long datatype though. Please advice. import java.util.*; import java.text.*; public class MillisecondToDate Читайте также: java ошибка 1618 как исправить
7. integer number too large forums.oracle.com
8. Integer number too large and :expected in switch forums.oracle.com
9. Integer number too large? — Mike Myatt forums.oracle.com
8 Answers 8
600851475143 cannot be represented as a 32-bit integer (type int ). It can be represented as a 64-bit integer (type long ). long literals in Java end with an «L»: 600851475143L
By default, java interpret all numeral literals as 32-bit integer values. If you want to explicitely specify that this is something bigger then 32-bit integer you should use suffix L for long values.
You need to use a long literal:
The java compiler tries to interpret 600851475143 as a constant value of type int by default. This causes an error since 600851475143 can not be represented with an int.
Since some Fonts make it hard to distinguish «1» and lower case «l» from each other you should always use the upper case «L».
I try to put 03145 in as an integer, but the complier keeps on complaining «integer number too large». What can I do to fix it? I can’t chop off the zero in the beginning.
the program works fine if I input «89345», the whole program is too big to be copied in here. This is from the main program
BarCode zip = new BarCode(20138);
5 Answers
You should show the exact lines of code. I’m guessing you are missing a semi-colon or something that will cause the compiler to see it as a much larger number. The leading 0 will treat it as octal, but that just gives you even more digits to work with!
But, something tells me it isn’t the compiler that is complaining. If you cannot cut of the leading 0, perhaps you are talking about reading from a data file, so you are getting a runtime exception. In that case, show the lines of code where you read in the data and your data file. It may be running things together.
I’m not sure what’s wrong.
I use Eclipse IDE for java, and When print the int k where it’s value is 03145, it does not error. It prints 1637
It must be interpreted as a different Base number by java or something
Try this in your browser window:
Parse it into a string, and use a RegExp to check if it has leading 0s, and then just substring it.
I’m having problems with a Mass property for planets, in Kilograms. Obviously a large integer, so I’ve tried declaring it as a long, Ulong, Int64, and even UInt64. However, when I try to enter in a new model of a planet, and put in the mass, I get the following error:
Here is my PlanetModel.cs where I’m describing the property:
Yet when I move over to my PlanetDataStore.cs, here is where I’m trying to build the object with data.
I get a red error squiggly over the first ‘3’ in my Mass, with the error above. Yet when I mouse over Mass, it reads: «long PlanetMode.Mass
Where is the miscommunication? Why is my property declared as a 64-bit integer, but the value stuck in 32-bit?
6 Answers 6
That is by no means obvious. The mass of the earth is not an integral number of kilograms. You shouldn’t be using any integral type for this application. Use integers for things that are genuinely integers, like the number of elements in a sequence.
Use double for physical quantities that are accurately measured to ten-ish decimal places. Mass, volume, length, force, and so on, should always be doubles.
This will also let you get rid of those hard-to-read numbers. Doubles let you use scientific notation because doubles are for science:
Also, while we’re looking at your solution, I note that for spherical planets, the volume can be computed from the radius. You might not want to store both; instead, just store one and calculate the other when you need it.
I note also that you have a single «distance» which seems to be the semi-major axis in the case of Mercury. Why are you storing only the semi-major axis, and why not call it what it is?
using BigDecimal for very large numbers
Is there anything that will make the output as a decimal number?
2 Answers 2
Yes, the only thing which you should use here is BigDecimal class. It’ll easily handle that complex value without burdening you.
The maximum supported double value is only around 1.7 * 10^ 308 as given by Double.MAX_VALUE specified for Java.
You need to use a BigDecimal to represent it: a number with an arbitrary number of bytes to represent numbers.
Better way to implement this:
A potential problem with this approach is that the precision is too high: Java will calculate all operations exactly resulting in numbers that have thousands of digits. Since every operation blows up the number of digits, within a few iterations, simple addition and multiplication operations become unfeasible.
You can solve this by defining a precision using the optional MathContext parameter: it determines on how precise the result should be. You can for instance use MathContext.DECIMAL128 :
This is approximately correct, after all the result of a should be:
Which is approximately correct according to Wolfram Alpha.
Furthermore I would advice to use a for and not a while if it is a for loop. Since while tends to create another type of infinity: an infinite loop ;).