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()));
Related
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.
I am new to Java and I get confused here. Why do I get an error when I want to convert string to int in java?
If I type in msi(a to e), and I want to use msii variable inside if statement to outside, and I can't, so I try using sout outside. But I get an error.
public static void main(String args[]){
Scanner i=new Scanner (System.in);
System.out.println("Name\t\t\t");
String nama=i.nextLine();
System.out.println("Nim\t\t\t");
String nim=i.nextLine();
System.out.println("grade\t\t");
String msi=i.next();
switch(msi) {
case "a||A":
{
msii=Integer.parseInt(msi);
msii=4;
break;
}
case "b||B":
{
msii=Integer.parseInt(msi);
msii=3;
break;
}
case "c||C":
{
msii=Integer.parseInt(msi);
msii=2;
break;
}
case "d||D":
{
msii=Integer.parseInt(msi);
msii=1;
break;
}
case "e||E":
{
msii=Integer.parseInt(msi);
msii=4;
break;
}
default:
System.out.println("tidak ada");
break;
}
System.out.println(+msii);
You didn't declare datatype for msii.
It must be declared as int msii globally or int msii=Integer.parseInt(msi);
Since you did not include any stacktrace of the Exception you get, I'm going to assume you get the NumberFormatException
From oracle:
public static int parseInt(String s)
throws NumberFormatException
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.
Parameters:
s - a String containing the int representation to be parsed
Returns:
the integer value represented by the argument in decimal.
Throws:
NumberFormatException - if the string does not contain a parsable integer.
Note that I marked the line
The characters in the string must all be decimal digits
This should already answer at least why you get an error.
You are trying to parse non decimal characters
We cant really help you more than that until you provide a more accurate description on what is it that you are trying to do.
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);
}
}
I have written a program that takes a ASCII character input (it actually takes a String then I use charAt(0)) into a JTextField then displays its hex, binary, int, and octal values using g2d.drawString(). I want the ability to also put in "integer" values (again actually being Strings) and display the info. In order to separate the "integer" values from the "char" inputs, I want to be able to input char values as they are, and integers using the pattern #i. This way, I can use an if statement to check if the "integer" pattern is followed, otherwise (else) evaluate the input as a ascii "char". How can I check if a String follows this pattern?
Example:
char input:
3 //I'll evaluate this as the ascii character value of 3
int input:
3i //I'll evaluate this as the integer value of 3
Note: Integer inputs could be multiple digits.
Look at the Pattern class. You will be able to do what you want with this.
Something like this?
if (str.length() == 1) {
char ch = charAt(0);
// code here
} else if (str.endsWith("i")) {
int num = Integer.parseInt(str.substring(0, str.length() - 1));
// code here
} else {
throw new IllegalArgumentException("Bad input: " + str);
}
The parseInt() will throw NumberFormatException if value preceding the i is not valid. Since that is a subclass of IllegalArgumentException, the code above will throw IllegalArgumentException for any bad text.
This code must validate input data from the findActions() method:
try {
System.out.println(findActions(lookingArea.substring(0, right)));// always printing valid number string
Integer.parseInt(findActions(lookingArea.substring(0, right)));// checking for number format
}
catch(NumberFormatException exc) {
System.out.println(exc);
}
But I always have java.lang.NumberFormatException: For input string: "*number*"
that is so strange, because checking with System.out.println(findActions(lookingArea.substring(0, right)));,
I get *number* like 10.0
Integer.parseInt doesn't expect the . character. If you're sure it can be converted to an int, then do one of the following:
Eliminate the ".0" off the end of the string before parsing it, or
Call Double.parseDouble, and cast the result to int.
Quoting the linked Javadocs above:
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.
10.0 is not an integer number. Instead, you can use:
int num = (int) Double.parseDouble(...);
One of the reason could be that your string is too long to convert into Integer type, So you can declare it as Long or Double based on the provided input.
Long l = Long.parseLong(str);