Java: NumberFormatException in converting string to integer - java

I want to retrieve value from textbox and convert it to integer. I wrote the following code but it throws a NumberFormatException.
String nop = no_of_people.getText().toString();
System.out.println(nop);
int nop1 = Integer.parseInt(nop);
System.out.println(nop1);
The first call to System.out.println prints me the number but converting to integer gives an exception. What am I doing wrong?

Note that the parsing will fail if there are any white spaces in your string. You could either trim the string first by using the .trim method or else, do a replace all using the .replaceAll("\\s+", "").
If you want to avoid such issues, I would recommend you use a Formatted Text Field or a Spinner.
The latter options will guarantee that you have numeric values and should avoid you the need of using try catch blocks.

Your TextBox may contain number with a white space. Try following edited code. You need to trim the TextBox Value before converting it to Integer. Also make sure that value is not exceeding to integer range.
String nop=(no_of_people.getText().toString().trim());
System.out.println(nop);
int nop1 = Integer.parseInt(nop);
System.out.println(nop1);

Try this:
int nop1 = Integer.parseInt(no_of_people.getText().toString().trim());
System.out.println(nop1);

I would suggest replacing all non-digit characters from String first converting to int:
replaceAll("\\D+", "");
You can use this code:
String nop=(no_of_people.getText().toString().replaceAll("\\D+", ""));
System.out.printf("nop=[%s]%n", nop);
int nop1 = Integer.parseInt(nop);
System.out.printf("nop1=[%d]%n", nop1);

Related

Multiplying ascii code and getting string back

I am trying to convert a string to ascii code and then multiplying that concatenation of the ascii codes by a number.
For example
String message = "Hello";
String result = "";
ArrayList arrayList = new ArrayList();
int temp;
for(int i = 0; i < message.length(); i++){
temp = (int) message.charAt(i);
result = result + String.value(temp).toString();
arrayList.add(String.valueOf(temp).toString());
}
I have tried two different ways, but there is always a catch with each one.
If I just concatenate all the ascii codes together into a string and I get 72101108108111 as my new string, the problem now is how can I get the original string back from this? This is because it is not obvious where each one character code starts and ends and the next one begins.
Another way I tried doing this was to use an array. I would receive |72|101|108|108|111| in an array. Obviously the codes are split here, but if I wanted to multiply this whole array (all the numbers as one number) by a number and then how would I get the array back together?
These are two different ways I have thought to solve this, but I have no idea how to get the string back out of these if I multiply the ascii by a number.
You don't need to modify the original string nor the ascii code string. Just have them both there, then whenever you need to get the numerical value of the string, just use X.valueOf(...)** method. Example,
final String message = "Hello";
final String result = "72101108108111";
long value = Long.valueOf(result);
If you do not want to store the two strings, then you should go with the array method. To get a numerical value, you simply concatenate all the strings in the array into one and use the X.valueOf(..) method.
And to get back the original string, use Integer.valueOf(...) on each string in the array, then cast each one to char.
System.out.println((char)Integer.valueOf("111").intValue());
** Note by X.valueOf(..), X doesn't have to be Long or Integer as I have shown. As you mentioned the value can get really large so BigInteger should be prefered above others

How to parse number string containing commas into an integer in java?

I'm getting NumberFormatException when I try to parse 265,858 with Integer.parseInt().
Is there any way to parse it into an integer?
Is this comma a decimal separator or are these two numbers? In the first case you must provide Locale to NumberFormat class that uses comma as decimal separator:
NumberFormat.getNumberInstance(Locale.FRANCE).parse("265,858")
This results in 265.858. But using US locale you'll get 265858:
NumberFormat.getNumberInstance(java.util.Locale.US).parse("265,858")
That's because in France they treat comma as decimal separator while in US - as grouping (thousand) separator.
If these are two numbers - String.split() them and parse two separate strings independently.
You can remove the , before parsing it to an int:
int i = Integer.parseInt(myNumberString.replaceAll(",", ""));
If it is one number & you want to remove separators, NumberFormat will return a number to you. Just make sure to use the correct Locale when using the getNumberInstance method.
For instance, some Locales swap the comma and decimal point to what you may be used to.
Then just use the intValue method to return an integer. You'll have to wrap the whole thing in a try/catch block though, to account for Parse Exceptions.
try {
NumberFormat ukFormat = NumberFormat.getNumberInstance(Locale.UK);
ukFormat.parse("265,858").intValue();
} catch(ParseException e) {
//Handle exception
}
One option would be to strip the commas:
"265,858".replaceAll(",","");
The first thing which clicks to me, assuming this is a single number, is...
String number = "265,858";
number.replaceAll(",","");
Integer num = Integer.parseInt(number);
Or you could use NumberFormat.parse, setting it to be integer only.
http://docs.oracle.com/javase/1.4.2/docs/api/java/text/NumberFormat.html#parse(java.lang.String)
Try this:
String x = "265,858 ";
x = x.split(",")[0];
System.out.println(Integer.parseInt(x));
EDIT :
if you want it rounded to the nearest Integer :
String x = "265,858 ";
x = x.replaceAll(",",".");
System.out.println(Math.round(Double.parseDouble(x)));

Ambiguousness in Android Java source

EditText ed1 = (EditText)findViewById( R.id.editText1 );
int a = Integer.parseInt( ed1.getText().toString() );
Does the above code get the input as numeric from the user and show it as a string?
My requirement is to get the input as integer and return as Strings. How do I do that?
Is the above code referencing that get the input as numeric from the user and show it as string?
The other way round - it's going through these steps:
Find the EditBox
Get the text from the edit box
Parse the text as a number
My requirement is to get the input as integer and return as Strings
Get the input from where? If you're getting the input from a user then it's probably already in a string form. If you're trying to convert an integer from somewhere else in the code, then you could use
String text = Integer.toString(number);
... or you could use a NumberFormat object, which would take different cultural information into account, allowing for grouping of digits etc.
EditText ed1=(EditText)findViewById(R.id.editText1);
String ed1Str = ed1.getText().toString().trim();
int a = Integer.parseInt(ed1Str);
Will make it available as an integer (int a) and as a string (String ed1Str)
The EditText.getText() returns Editable object and you have to convert it to string. You cannot get the number directly from edit text. You can access the text returned from EditText, convert it to String and then covert it into number as you have implemented.
do little modification in above code ed1.setInputType(InputType.TYPE_CLASS_NUMBER);
that will make your edittext only to accept integer values..

java convert to int

I am trying to convert to int like this, but I am getting an exception.
String strHexNumber = "0x1";
int decimalNumber = Integer.parseInt(strHexNumber, 16);
Exception in thread "main" java.lang.NumberFormatException: For input string: "0x1"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:458)
It would be a great help if someone can fix it.
Thanks.
That's because the 0x prefix is not allowed. It's only a Java language thing.
String strHexNumber = "F777";
int decimalNumber = Integer.parseInt(strHexNumber, 16);
System.out.println(decimalNumber);
If you want to parse strings with leading 0x then use the .decode methods available on Integer, Long etc.
int value = Integer.decode("0x12AF");
System.out.println(value);
Sure - you need to get rid of the "0x" part if you want to use parseInt:
int parsed = Integer.parseInt("100", 16);
System.out.println(parsed); // 256
If you know your value will start with "0x" you can just use:
String prefixStripped = hexNumber.substring(2);
Otherwise, just test for it:
number = number.startsWith("0x") ? number.substring(2) : number;
Note that you should think about how negative numbers will be represented too.
EDIT: Adam's solution using decode will certainly work, but if you already know the radix then IMO it's clearer to state it explicitly than to have it inferred - particularly if it would surprise people for "035" to be treated as octal, for example. Each method is appropriate at different times, of course, so it's worth knowing about both. Pick whichever one handles your particular situation most cleanly and clearly.
Integer.parseInt can only parse strings that are formatted to look just like an int. So you can parse "0" or "12343" or "-56" but not "0x1".
You need to strip off the 0x from the front of the string before you ask the Integer class to parse it. The parseInt method expects the string passed in to be only numbers/letters of the specified radix.
try using this code here:-
import java.io.*;
import java.lang.*;
public class HexaToInteger{
public static void main(String[] args) throws IOException{
BufferedReader read =
new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the hexadecimal value:!");
String s = read.readLine();
int i = Integer.valueOf(s, 16).intValue();
System.out.println("Integer:=" + i);
}
}
Yeah, Integer is still expecting some kind of String of numbers. that x is really going to mess things up.
Depending on the size of the hex, you may need to use a BigInteger (you can probably skip the "L" check and trim in yours ;-) ):
// Convert HEX to decimal
if (category.startsWith("0X") && category.endsWith("L")) {
category = new BigInteger(category.substring(2, category.length() - 1), 16).toString();
} else if (category.startsWith("0X")) {
category = new BigInteger(category.substring(2, category.length()), 16).toString();
}

Is J2ME's Integer.parseInt() broken?

While writing a game for J2ME we ran into an issue using java.lang.Integer.parseInt()
We have several constant values defined as hex values, for example:
CHARACTER_RED = 0xFFAAA005;
During the game the value is serialized and is received through a network connection, coming in as a string representation of the hex value. In order to parse it back to an int we unsuccesfully tried the following:
// Response contains the value "ffAAA005" for "characterId"
string hexValue = response.get("characterId");
// The following throws a NumberFormatException
int value = Integer.parseInt(hexValue, 16);
Then I ran some tests and tried this:
string hexValue = Integer.toHexString(0xFFAAA005);
// The following throws a NumberFormatException
int value = Integer.parseInt(hexValue, 16);
This is the exception from the actual code:
java.lang.NumberFormatException: ffaaa005
at java.lang.Integer.parseInt(Integer.java:462)
at net.triadgames.acertijo.GameMIDlet.startMIDlet(GameMIDlet.java:109)
This I must admit, baffled me. Looking at the parseInt code the NumberFormatException seems to be thrown when the number being parsed "crosses" the "negative/positive boundary" (perhaps someone can edit in the right jargon for this?).
Is this the expected behavior for the Integer.parseInt function? In the end I had to write my own hex string parsing function, and I was quite displeased with the provided implementation.
In other words, was my expectation of having Integer.parseInt() work on the hex string representation of an integer misguided?
EDIT: In my initial posting I wrote 0xFFFAAA005 instead of 0xFFAAA005. I've since corrected that mistake.
The String you are parsing is too large to fit in an int. In Java, an int is a signed, 32-bit data type. Your string requires at least 36 bits.
Your (positive) value is still too large to fit in a signed 32-bit int.
Do realize that your input (4289372165) overflows the maximum size of an int (2147483647)?
Try parsing the value as a long and trim the leading "0x" off the string before you parse it:
public class Program {
public static void main(String[] args) {
String input = "0xFFFAAA005";
long value = Long.parseLong(input.substring(2), 16);
System.out.print(value);
}
}
I'm not a java dev, but I'd guess parseInt only works with integers. 0xFFFAAA005 has 9 hex digits, so it's a long, not an int. My guess is it's complaining because you asked it to parse a number that's bigger than it's result data type.
Your number seems to be too large to fit in an int, try using Long.parseLong() instead.
Also, the string doesn't seem to get parsed if you have 0x in your string, so try to cut that off.

Categories