I want to find if given String "99999999999999999999999999" or any massive number which would not fit in any datatype.I would like to find if that number is bigger than Integer.MAX_VALUE
Use BigInteger
BigInteger maxInt = BigInteger.valueOf(Integer.MAX_VALUE);
BigInteger value = new BigInteger("whatever");
if (value.compareTo(maxInt) > 0)
{
// larger
}
You could construct a BigInteger object from the string and then compare that BigInteger to Integer.MAX_VALUE.
You can call parseInt and catch NumberFormatException, which will be thrown if the number is too large (though it will also be thrown if the String has non-numeric characters).
If you want to avoid the exception, you can run the following checks:
If the String has more than 10 characters (or 11 if the first character is '-' or '+'), it must be larger than Integer.MAX_VALUE or smaller than Integer.MIN_VALUE.
Otherwise, call Long.parseLong() and compare the result to Integer.MAX_VALUE.
You can parse it as an int and catch an exception or BigInteger, or you can do a String comparison.
static final String MAX_INT_STR = Integer.toString(Integer.MAX_VALUE);
public static boolean checkInt(String s) {
return s.length() > MAX_INT_STR.length() || s.compareTo(MAX_INT_STR) > 0;
}
This could be used to avoid throwing some Exceptions before trying to parse it.
NOTE: This doesn't check that it only contains digits, but if it's a positive number it will check it is in bounds without parsing the string.
Try the following code to check if it's too big to fit inside an integer:
String num = "99999999999999999999999999";
try {
Integer.parseInt(num);
} catch(NumberFormatException ex) {
System.out.println("String did not fit in integer datatype");
}
This code will attempt to parse num into an integer, we can catch whenever that goes wrong and execute code when that happens (in this case a simple println).
From parseInt():
Throws: NumberFormatException - if the string does not contain a
parsable integer.
Related
public int reverse(int x) {
String xString=String.valueOf(Math.abs(x));
StringBuffer reverseX=new StringBuffer (xString);
if (x>=Integer.MIN_VALUE & x<=Integer.MAX_VALUE) {
reverseX=reverseX.reverse();
if (x<0)
reverseX=reverseX.insert(0,"-");
return Integer.parseInt(reverseX.toString());
}
else
return 0;
}
Runtime Error Message:
Line 12: java.lang.NumberFormatException: For input string:
"9646324351"
Last executed input:
1534236469
What's wrong? help plz Orz!!!
if you try to call your method with the value:
reverse(9646324351);
You get an Compiler error, which leads you to the Problem:
The literal 9646324351 of type int is out of range
So i do not understand why you can get an error in your method.
Use a long/Long or a BigInterger in your program
Here you can rad about the data types and which range they cover
That number is too large to be parsed as an Interger, it exceeds Integer.MAX_VALUE.
Rather use Long.parseLong
Use biginteger class instead of Integer
Read the docs https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html
public long reverse(int x) {
String xString=String.valueOf(Math.abs(x));
StringBuffer reverseX=new StringBuffer (xString);
if (x>=Integer.MIN_VALUE & x<=Integer.MAX_VALUE) {
reverseX=reverseX.reverse();
if (x<0)
reverseX=reverseX.insert(0,"-");
return Long.parseLong(reverseX.toString());
}
else
return 0L;
}
You can try above code.
As this 9646324351 value is out of range of int type.You need to provide larger datatype for this String to numeric conversion.
As we know
double's range > long's range >int's range
Also you can try BigInteger
Hope this will help you.
Accepting user input one character at a time, the largest acceptable integer before I have to limit input seems to be (10^8)-1. I was mildly surprised that it wasn't Integer.MAX_VALUE. Why isn't it?
Code written out in the Keyboard class that extends KeyAdapter:
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class Keyboard extends KeyAdapter{
private final int MAX_TESTABLE = 99999999;
private final int VK_NUMBER = 48; //ASCII 0 starts here
private final int VK_NUMBERPAD = 96; //ASCII numberpad offset
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
if(((char)key == '0' ||
(char)key == '1' ||
(char)key == '2' ||
(char)key == '3' ||
(char)key == '4' ||
(char)key == '5' ||
(char)key == '6' ||
(char)key == '7' ||
(char)key == '8' ||
(char)key == '9')){
if(Integer.parseInt(Launcher.inputString+(char)key) <= MAX_TESTABLE){
Launcher.inputString += (char)key;
}
}else if (e.getKeyLocation() == KeyEvent.KEY_LOCATION_NUMPAD){
if(Integer.parseInt(Launcher.inputString+(char)(VK_NUMBER+key-VK_NUMBERPAD)) <= MAX_TESTABLE){
Launcher.inputString += (char)(VK_NUMBER+key-VK_NUMBERPAD);
}
}
System.out.println(
"Key "+key+" pressed\n"+
"Input string: "+Launcher.inputString
);
}
}
Other classes linked here:
Launcher: http://pastebin.com/a5xPydse
Window: http://pastebin.com/BDKNSUya
EDIT: Here is what ended up being the solution, as found by Vaysym. I'm pasting it here to make it easier for anyone in the future who might look this up:
The answer is in the question: (10^8)-1
Here's why:
In Java, the primitive type int is allowed 4 bytes of memory: 2^32. Because it is signed, we have to allocate half of the 32 bits for the negative spectrum. We also have to subtract one from the total (which, because it's an odd number, happens to actually subtract from the positive spectrum). So our total range becomes (2^(32-1))-1 = 2,147,483,647
Because we are testing USING int here, this is the maximum testable number. So on the right operand the most we can check for is (2^31)-1, so we get this code: if(Integer.parseInt(inputString+(char)key) < 2147483647){}
This will still throw an exception because the left operand can end up being higher than Integer.MAX_VALUE, so we have to limit inputString before it gets there. Because the input is received one character at a time and the largest digit you can input, 9, is greater than the left-most digit of (2^31)-1, which is a 2, the closest we can get to Integer.MAX_VALUE is an entire order of magnitude short; Integer.MAX_VALUE has 10 digits, so we cannot test further than 9 digits: (10^(10-1))-1 = (10^9)-1 = 999,999,999
Because we're testing inputString plus the next inputted digit, we have to go down another order of magnitude, bringing us to the final answer of (10^8)-1
Final code:
if(Integer.parseInt(inputString+(char)key) < 999999999){}
--------------------
Original answer:
The problem with how you're using Integer.parseInt is (quoted from my comment):
If you pass in a value larger then 2147483647 to Integer.parseInt(),
it will throw the exception before it can even compare it to <
2147483647, because you're already trying to assign a value to large
for a Integer in your call to parseInt().
The exception will be thrown if you pass in anything other then a number under 2147483647, including an empty String.
To get around this, try using a try-catch block:
try
{
Integer.parseInt(inputString);
//No exception thrown, this is a valid Integer!
}
catch(NumberFormatException e)
{
//NumberFormatException! "inputString" Can not be an Integer!
}
If an exception is thrown by Integer.parseInt(), the code in the catch block will run, otherwise the code in the try block will continue running. By catching the exception, it won't cause your program to crash.
If you don't want to use try/catch, you'll just have to limit what the user can type. You can use Long and parseLong instead of Integer to allow larger numbers, but that will still throw an exception if you enter a non-number.
Update: You could use this to check if input string will fit into an Integer (if the number is smaller then a long, which it probably will be), but unfortunately it will still throw the exception if you enter something that isn't a number.
if(Long.parseLong(inputString+(char)key) > 2147483647)
{
//"inputString+(char)key" Will fit into an Integer!
inputString += (char)key;
}
else
{
//"inputString+(char)key" Will NOT fit into an Integer!
}
Update 2: Looking at your edit, you're quite close. What's happening is when you add the char, it is getting added to end of the String, then parseInt is preformed on it. So adding the string "999999999" to the char (let's say it has a value of 1), will equal 9999999991 (or 9,999,999,991 when it's converted to a number) not 1,000,000,000. The number is then larger then an Integer by the time parseInt() is preformed on it.
Also, casting a int to a char will print out the ASCII character corresponding with the int's number, see this question for more on that.
To get the output you're looking for, try casting your inputString and key before adding them together. Example: (With inputString = 50 and key = 50)
Integer.parseInt(inputString) + (int)key // = 100
Instead of:
Integer.parseInt(inputString+(char)key) // Would equal 5050, but because 50 is the ASCCI character for 2, it will be 502.
Note that this will still throw an exception if you try to parse a number larger then 2147483647, so please consider enclosing it with a try/catch block.
Hope this helps you understand what's happening.
Try removing (char)key when parsing the string. Any value 0-9 added at the end will always overflow the max integer value unless the first digit is a 1. 999,999,999 + key = 9,999,999,99x > 2147483647. You could use a long and check if the value is greater than Integer.MAX_VALUE.
String number = inputString+(char)(48+key-96);
if (Long.parseLong(number) >= Integer.MAX_VALUE) {
if(Integer.parseInt(inputString+(char)(48+key-96)) < 999999999){
inputString += (char) key;
}
}
You are parsing the string to test if the integer value is to large for integer to fit. If the value is to large for integer, then the parsing throws an error, because the result cannot be stored in an integer.
You should compare the 2 numbers lexographically as strings if the string is 10 digits long.
YourNumberAsString.compare(new String(Integer.MaxValue));
The result will tell you which number is bigger.
the value 0 if the argument string is equal to this string; a value
less than 0 if this string is lexicographically less than the string
argument; and a value greater than 0 if this string is
lexicographically greater than the string argument.
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#compareTo(java.lang.String)
Should be Integer.MAX_VALUE
Tried this and working
System.out.println(Integer.parseInt(String.valueOf(Integer.MAX_VALUE)));
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "9999999999"
your input is definitely 9,999,999,999 and the maximum of integer is only 2,147,483,647
If you just want to check whether input is correct or not you can use this
boolean tryParseInt(String value) {
try {
Integer.parseInt(value);
return true;
} catch (NumberFormatException e) {
return false;
}
}
if(tryParseInt(inputString+(char)key)){
//input comes from the standard keyboard
inputString += (char)key;
}
}else if(e.getKeyLocation() == KeyEvent.KEY_LOCATION_NUMPAD){
if(tryParseInt(inputString+(char)(48+key-96))){
//input comes from the numberpad
inputString += (char)(48+key-96);
}
}
Given the String representation of an int, I want to check for overflow.
I know how to convert a String from int using java's built in functions like parseInt.
But what if the String is so large that it might not fit into an int?
String str = "214748364781";
int res = Integer.parseInt(str);
I tried to check the sign of the String representation, do parseInt and if the signs don't match then I can say that it does overflow since int wraps around but when I actually ran it it threw a NumberFormat exception.
NumberFormat is thrown for any bad formatted string so it's not a guarantee for overflow.
So I can check that the input string's format is correct (all numbers) and then do parseInt then if I get NumberFormat I can conclude that the error's due to overflow.
However, I feel like there should be a shorter way of doing this check.
Parse it as a Long and if it works parse it as an Integer, if it throws and Exception at that point, it overflows.
OR
Parse it as a Long and check if it is bigger than Integer.MAX_VALUE
You could parse it as a BigInteger and check if it's larger than Integer.MAX_VALUE:
BigInteger maxIntBigInteger = BigInteger.valueOf(Integer.MAX_VALUE);
String str = "214748364781";
BigInteger bi = new BigInteger(str);
if (bi.compareTo(maxIntBigInteger) > 0) {
System.out.println("Number is too big");
} else {
int res = bi.intValue();
System.out.println(res);
}
Just to give you a different option, if all you want to do is check if your string will not overflow you could compare lexicographically. String comparison is generally much faster than parsing to a number.
Assuming only positive integers.
String number = "2147483649";
String int_max = "2147483647";
if (number.length() > int_max.length())
{
System.out.println("OVERFLOW");
}
else if (number.length() == int_max.length()){
int comparison = number.compareTo(int_max);
System.out.println(comparison > 0 ? "OVERFLOW" : "");
}
Now, in a real life scenario, if you can potentially have big integers you should just use Long or BigInteger as suggested in other answers.
Hope this helps.
If you're using Java 8, you can parse it as type Long and then use Math.toIntExact(long value) to get the int value. This throws an unchecked ArithmeticException if there is an overflow.
Here is an example with your code:
String str = "214748364781";
int res = Math.toIntExact(Long.parseLong(str));
Or to simplify further:
int res = Math.toIntExact(Long.parseLong("214748364781"));
And as expected we get the integer overflow exception as follows:
Exception in thread "main" java.lang.ArithmeticException: integer overflow
at java.lang.Math.toIntExact(Math.java:1011)
I have a file containing list of values which may be just a string or an integer.
bhushan 21
kedar 20
When i read values in a string array i also want to perform some arithmetic operations if the data that i have is an integer or double. How do i check whether the data that i have is an integer, double or a string?
I am currently storing all values in a string array using split function and whenever i want to take average of all numbers i convert the numbers that i am sure of to integers or double and then perform arithmetic operations. I want to write a method that will tell me what exactly is the type of that value.
Using a regular expression should be the most efficient way. Other expressions can be used to further look for floating point numbers, etc.
String input = "12345";
java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(".*[^0-9].*");
if( pattern.matcher(input).matches() )
System.out.println("Its a number");
else
System.out.println("Its not a number");
You can also use the Integer.parseInt() or Double.parseDouble() methods, however, they will throw a NumberFormatException if the input does not conform.
You can do that with simple function;
public static boolean isValueInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;//For example "bhushan"
}
return true;// For example "21"
}
It will throw NumberFormatException if it is a String
You can try to cast it from string to int.
try{
int result = Integer.parseInt(stringValue);
} catch (NumberFormatException nfe) {
}
You usually would use something like regular expression for that. e.g.
String number = "daaaa";
Pattern digitPattern = Pattern.compile("\\d{6}");
if (digitPattern.matcher(number).matches()) {
System.out.println(number + " is a number.");
}
i have learned that to convert charsequence to integer we can use this statement
String cs="123";
int number = Integer.parseInt(cs.toString());
what if
cs = "++-+--25";
will this statement still run and give answer -25 according to string given??
You are end up with a NumberFormatException since ++-+--25 is not a valid integer.
See the docs of parseInt()
Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method.
So you are allowed to do
CharSequence cs = "-25"; //gives you -25
and
CharSequence cs = "+25"; //gives you 25
Otherwise ,take necessary steps to face the Exception :)
So know the char Sequence is a valid string just write a simple method to return true or false and then proceed further
public static boolean {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false; // no boss you entered a wrong format
}
return true; //valid integer
}
Then your code looks like
if(isInteger(cs.toString())){
int number = Integer.parseInt(cs.toString());
// proceed remaining
}else{
// No, Operation cannot be completed.Give proper input.
}
Answer to your question is code will run and throw Exception as "++-+--25" is not a valid int,
java.lang.NumberFormatException: For input string: "++-+--25"
You will get
java.lang.NumberFormatException: For input string: "++-+--25"
Tested example :
CharSequence cs = "++-+--25";
System.out.println("" + Integer.parseInt(cs.toString()));