Why my code is giving NumberFormatException? - java

I have code like this :
int [] arrayOfImages = new int[namesOfSubjectsColorCode.size()];
int y = 0;
for (int x = 0 ; x<namesOfSubjectsColorCode.size();x++) {
nameOfColorCode = namesOfSubjectsColorCode.get(x);
String str = "com" + "." + "nyurals" + "." + "R" + "." + "drawable" + "." + nameOfColorCode;
arrayOfImages[y] = Integer.parseInt(str);
// Integer.parseInt(str);
y++;
}
Here, I have created integer array. Then, I have created string and by using Integer.parseInt() I want to convert it to int so that, my array of integer should generate dynamically. It is giving NumberFormatException.
Please suggest to me a solution for this.

There is no way for this String to be reasonably turned into an int.
String str = "com" + "." + "nyurals" + "." + "R" + "." + "drawable" + "." + nameOfColorCode;
Something like this would be expected:
String str = "1";

Its obvious that it gives you NumberFormatException. Look at your code :
Your str variable contains String which cant parse into Integer value.

Argument for Integer.parseInt() is invalid, you can't pass it string like "com.nyurals.." etc
From the docs:
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.
And that's exactly what you're getting: NumberFormatException.
EDIT:
You probably want to do something like this:
nameOfColorCode = namesOfSubjectsColorCode.get(x);
String str = "" + nameOfColorCode;
int resourceId = this.getResources().getIdentifier(str, "drawable", this.getPackageName());
arrayOfImages[y] = resourceId;
y++;

If you want to get the int (id) of a resource than you should use
Resources res = activity.getResources();
res.getIdentifier("name","resourceType",activty.getPackageName());
change the name with actual name and resourceType with actual resource type (drawable,color,etc);
As others wrote you don't have an int in your string, it's just an int and not a reference to resoruce

You can access the constants you're trying to reference via http://docs.oracle.com/javase/tutorial/reflect/ but you really don't want to do that.
You'd be better served putting the int's in some form of map of which you can then select some kind of subset dependent on changing information

Integer.parseInt() expects to be given an integer of some sort, not a string of the format com.nyurals.R.drawable.<<nameOfColorCode>>.
Generally, in Android, you would access the variables directly with something like:
R.drawable.SomeName
rather than trying to decode (or, in your case, directly using) the string to get a value.
For example, the following code gets the surface view based on an ID:
SurfaceView sv = (SurfaceView)findViewById(R.id.PfrRightAntiView);
If you do need to dynamically extract a resource based on a string known only at runtime, look into Resources.getIdentifier(), an example of which can be found here.
As per this article, that method may not be the fastest. It may be better to use the reflection method as shown in that link.

May your str returns null so Integer.parseInt(null) return number format exception

Related

Java: Type-identification by IDs instead of names?

String s = "abc";
Integer i = 123;
System.out.println (s.getClass().getTypeName());
System.out.println (i.getClass().getTypeName());
Output is
java.lang.String
java.lang.Integer
I'd like to have some smaller type-identification (like a unique number). I need to store it and therefore I would prefer in a shorter way.
You can hash the string, like hashCode() , which is available on any object and it returns an int. Basically, the int is a simple number which needs less storage space and has higher performance. However, the calculation of a hash needs some time.
I say "like", because you can't actually use that method. The method is not guaranteed to return the same result for different executions of the application, so you must not store it in a database.
But there are hash functions that guarantee the same result, e.g. simple ones like MD5. (How can I generate an MD5 hash?)
However, note that a hash is a one-way conversion. If, for whatever reason (possible an unknown reason at this point in time), you need the type as the name again, there's no way to do that.
Think the proposed solutions in the comments with getSimpleName (RedCam) and hashCode of the Class (Ricky Mo, kutschkern) are the best for my requirements. Thanks!
String s = "abc";
String ss = "abcd";
Integer i = 123;
Integer ii = 1234;
System.out.println (s.getClass().getSimpleName() + " " + s.getClass().hashCode());
System.out.println (ss.getClass().getSimpleName() + " " + ss.getClass().hashCode());
System.out.println (i.getClass().getSimpleName() + " " + i.getClass().hashCode());
System.out.println (ii.getClass().getSimpleName() + " " + ii.getClass().hashCode());
Output
String 349885916
String 349885916
Integer 1627674070
Integer 1627674070
You could use a switch statement to assign a 'tag' you can think of yourself to define them with a shorter 'id':
int id = 0;
switch(s.getClass().getTypeName()) {
case "java.lang.String":
id = 1;
break;
case "java.lang.Integer":
id = 2;
break;
default:
id = 0;
}
Compress the Strings. The range of characters is not very big, so compression should work pretty well.
GZipInputStream / GZipOutputStream should work well.
There is no numerical ID for classes, just the String. So you have to come up with your own method of assigning IDs.

Using only 1 System.out.print() instead of 3. More details below [duplicate]

I am trying to concatenate strings in Java. Why isn't this working?
public class StackOverflowTest {
public static void main(String args[]) {
int theNumber = 42;
System.out.println("Your number is " . theNumber . "!");
}
}
You can concatenate Strings using the + operator:
System.out.println("Your number is " + theNumber + "!");
theNumber is implicitly converted to the String "42".
The concatenation operator in java is +, not .
Read this (including all subsections) before you start. Try to stop thinking the php way ;)
To broaden your view on using strings in Java - the + operator for strings is actually transformed (by the compiler) into something similar to:
new StringBuilder().append("firstString").append("secondString").toString()
There are two basic answers to this question:
[simple] Use the + operator (string concatenation). "your number is" + theNumber + "!" (as noted elsewhere)
[less simple]: Use StringBuilder (or StringBuffer).
StringBuilder value;
value.append("your number is");
value.append(theNumber);
value.append("!");
value.toString();
I recommend against stacking operations like this:
new StringBuilder().append("I").append("like to write").append("confusing code");
Edit: starting in java 5 the string concatenation operator is translated into StringBuilder calls by the compiler. Because of this, both methods above are equal.
Note: Spaceisavaluablecommodity,asthissentancedemonstrates.
Caveat: Example 1 below generates multiple StringBuilder instances and is less efficient than example 2 below
Example 1
String Blam = one + two;
Blam += three + four;
Blam += five + six;
Example 2
String Blam = one + two + three + four + five + six;
Out of the box you have 3 ways to inject the value of a variable into a String as you try to achieve:
1. The simplest way
You can simply use the operator + between a String and any object or primitive type, it will automatically concatenate the String and
In case of an object, the value of String.valueOf(obj) corresponding to the String "null" if obj is null otherwise the value of obj.toString().
In case of a primitive type, the equivalent of String.valueOf(<primitive-type>).
Example with a non null object:
Integer theNumber = 42;
System.out.println("Your number is " + theNumber + "!");
Output:
Your number is 42!
Example with a null object:
Integer theNumber = null;
System.out.println("Your number is " + theNumber + "!");
Output:
Your number is null!
Example with a primitive type:
int theNumber = 42;
System.out.println("Your number is " + theNumber + "!");
Output:
Your number is 42!
2. The explicit way and potentially the most efficient one
You can use StringBuilder (or StringBuffer the thread-safe outdated counterpart) to build your String using the append methods.
Example:
int theNumber = 42;
StringBuilder buffer = new StringBuilder()
.append("Your number is ").append(theNumber).append('!');
System.out.println(buffer.toString()); // or simply System.out.println(buffer)
Output:
Your number is 42!
Behind the scene, this is actually how recent java compilers convert all the String concatenations done with the operator +, the only difference with the previous way is that you have the full control.
Indeed, the compilers will use the default constructor so the default capacity (16) as they have no idea what would be the final length of the String to build, which means that if the final length is greater than 16, the capacity will be necessarily extended which has price in term of performances.
So if you know in advance that the size of your final String will be greater than 16, it will be much more efficient to use this approach to provide a better initial capacity. For instance, in our example we create a String whose length is greater than 16, so for better performances it should be rewritten as next:
Example optimized :
int theNumber = 42;
StringBuilder buffer = new StringBuilder(18)
.append("Your number is ").append(theNumber).append('!');
System.out.println(buffer)
Output:
Your number is 42!
3. The most readable way
You can use the methods String.format(locale, format, args) or String.format(format, args) that both rely on a Formatter to build your String. This allows you to specify the format of your final String by using place holders that will be replaced by the value of the arguments.
Example:
int theNumber = 42;
System.out.println(String.format("Your number is %d!", theNumber));
// Or if we need to print only we can use printf
System.out.printf("Your number is still %d with printf!%n", theNumber);
Output:
Your number is 42!
Your number is still 42 with printf!
The most interesting aspect with this approach is the fact that we have a clear idea of what will be the final String because it is much more easy to read so it is much more easy to maintain.
The java 8 way:
StringJoiner sj1 = new StringJoiner(", ");
String joined = sj1.add("one").add("two").toString();
// one, two
System.out.println(joined);
StringJoiner sj2 = new StringJoiner(", ","{", "}");
String joined2 = sj2.add("Jake").add("John").add("Carl").toString();
// {Jake, John, Carl}
System.out.println(joined2);
You must be a PHP programmer.
Use a + sign.
System.out.println("Your number is " + theNumber + "!");
"+" instead of "."
Use + for string concatenation.
"Your number is " + theNumber + "!"
This should work
public class StackOverflowTest
{
public static void main(String args[])
{
int theNumber = 42;
System.out.println("Your number is " + theNumber + "!");
}
}
For exact concatenation operation of two string please use:
file_names = file_names.concat(file_names1);
In your case use + instead of .
For better performance use str1.concat(str2) where str1 and str2 are string variables.
String.join( delimiter , stringA , stringB , … )
As of Java 8 and later, we can use String.join.
Caveat: You must pass all String or CharSequence objects. So your int variable 42 does not work directly. One alternative is using an object rather than primitive, and then calling toString.
Integer theNumber = 42;
String output =
String // `String` class in Java 8 and later gained the new `join` method.
.join( // Static method on the `String` class.
"" , // Delimiter.
"Your number is " , theNumber.toString() , "!" ) ; // A series of `String` or `CharSequence` objects that you want to join.
) // Returns a `String` object of all the objects joined together separated by the delimiter.
;
Dump to console.
System.out.println( output ) ;
See this code run live at IdeOne.com.
In java concatenate symbol is "+".
If you are trying to concatenate two or three strings while using jdbc then use this:
String u = t1.getString();
String v = t2.getString();
String w = t3.getString();
String X = u + "" + v + "" + w;
st.setString(1, X);
Here "" is used for space only.
In Java, the concatenation symbol is "+", not ".".
"+" not "."
But be careful with String concatenation. Here's a link introducing some thoughts from IBM DeveloperWorks.
You can concatenate Strings using the + operator:
String a="hello ";
String b="world.";
System.out.println(a+b);
Output:
hello world.
That's it
So from the able answer's you might have got the answer for why your snippet is not working. Now I'll add my suggestions on how to do it effectively. This article is a good place where the author speaks about different way to concatenate the string and also given the time comparison results between various results.
Different ways by which Strings could be concatenated in Java
By using + operator (20 + "")
By using concat method in String class
Using StringBuffer
By using StringBuilder
Method 1:
This is a non-recommended way of doing. Why? When you use it with integers and characters you should be explicitly very conscious of transforming the integer to toString() before appending the string or else it would treat the characters to ASCI int's and would perform addition on the top.
String temp = "" + 200 + 'B';
//This is translated internally into,
new StringBuilder().append( "" ).append( 200 ).append('B').toString();
Method 2:
This is the inner concat method's implementation
public String concat(String str) {
int olen = str.length();
if (olen == 0) {
return this;
}
if (coder() == str.coder()) {
byte[] val = this.value;
byte[] oval = str.value;
int len = val.length + oval.length;
byte[] buf = Arrays.copyOf(val, len);
System.arraycopy(oval, 0, buf, val.length, oval.length);
return new String(buf, coder);
}
int len = length();
byte[] buf = StringUTF16.newBytesFor(len + olen);
getBytes(buf, 0, UTF16);
str.getBytes(buf, len, UTF16);
return new String(buf, UTF16);
}
This creates a new buffer each time and copies the old content to the newly allocated buffer. So, this is would be too slow when you do it on more Strings.
Method 3:
This is thread safe and comparatively fast compared to (1) and (2). This uses StringBuilder internally and when it allocates new memory for the buffer (say it's current size is 10) it would increment it's 2*size + 2 (which is 22). So when the array becomes bigger and bigger this would really perform better as it need not allocate buffer size each and every time for every append call.
private int newCapacity(int minCapacity) {
// overflow-conscious code
int oldCapacity = value.length >> coder;
int newCapacity = (oldCapacity << 1) + 2;
if (newCapacity - minCapacity < 0) {
newCapacity = minCapacity;
}
int SAFE_BOUND = MAX_ARRAY_SIZE >> coder;
return (newCapacity <= 0 || SAFE_BOUND - newCapacity < 0)
? hugeCapacity(minCapacity)
: newCapacity;
}
private int hugeCapacity(int minCapacity) {
int SAFE_BOUND = MAX_ARRAY_SIZE >> coder;
int UNSAFE_BOUND = Integer.MAX_VALUE >> coder;
if (UNSAFE_BOUND - minCapacity < 0) { // overflow
throw new OutOfMemoryError();
}
return (minCapacity > SAFE_BOUND)
? minCapacity : SAFE_BOUND;
}
Method 4
StringBuilder would be the fastest one for String concatenation since it's not thread safe. Unless you are very sure that your class which uses this is single ton I would highly recommend not to use this one.
In short, use StringBuffer until you are not sure that your code could be used by multiple threads. If you are damn sure, that your class is singleton then go ahead with StringBuilder for concatenation.
First method: You could use "+" sign for concatenating strings, but this always happens in print.
Another way: The String class includes a method for concatenating two strings: string1.concat(string2);
import com.google.common.base.Joiner;
String delimiter = "";
Joiner.on(delimiter).join(Lists.newArrayList("Your number is ", 47, "!"));
This may be overkill to answer the op's question, but it is good to know about for more complex join operations. This stackoverflow question ranks highly in general google searches in this area, so good to know.
you can use stringbuffer, stringbuilder, and as everyone before me mentioned, "+". I'm not sure how fast "+" is (I think it is the fastest for shorter strings), but for longer I think builder and buffer are about equal (builder is slightly faster because it's not synchronized).
here is an example to read and concatenate 2 string without using 3rd variable:
public class Demo {
public static void main(String args[]) throws Exception {
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(r);
System.out.println("enter your first string");
String str1 = br.readLine();
System.out.println("enter your second string");
String str2 = br.readLine();
System.out.println("concatenated string is:" + str1 + str2);
}
}
There are multiple ways to do so, but Oracle and IBM say that using +, is a bad practice, because essentially every time you concatenate String, you end up creating additional objects in memory. It will utilize extra space in JVM, and your program may be out of space, or slow down.
Using StringBuilder or StringBuffer is best way to go with it. Please look at Nicolas Fillato's comment above for example related to StringBuffer.
String first = "I eat"; String second = "all the rats.";
System.out.println(first+second);
Using "+" symbol u can concatenate strings.
String a="I";
String b="Love.";
String c="Java.";
System.out.println(a+b+c);

evaluating variable int/string

int x = 20;
double d = 3.1416;
String s ="H";
those are my variables and I have to give the type the next lines evaluate to.
d/x + "";
is evaluating to double variable type (0.15708), is that correct?
You'd be right if we didn't have that pesky "" at the end!
Add "" to the end of something like this makes it into a String. It can actually be a handy shortcut - instead of having to use something like String.valueOf(), you could just do 4/2 + "", which makes it into a string.
To reiterate,
d/x would be a double, since you are adding a floating point.
But a double + "" = String.
I hope that helps. Good luck :)
You are wrong.
d/x + ""; is a String. This happens because when you are using the + operator, if any of the 2 sides is a String, then string concatenation happens and of course the result is a String.
By the way you can check that indeed it is a String by using the getClass() method. Note that if you remove the "" and use the getClass() you will get an error. This happens because d/x is a double, i.e a primitive type, so it can't use the method getClass(). In your example:
System.out.println((d/x + "").getClass()); will return java.lang.String

How to escape special characters from JSON when assign it to Java String

im tring to assign value from json to java String. but JSON value is including some special charactor ("\"). when i was try to assigen it to the string it gives error.
this is the JSON value,
"ValueDate":"\/Date(1440959400000+0530)\/"
this is how i trying to use it.
HistoryVO.setValueDate(DataUtil.getDateForUnixDate(historyJson.getString("ValueDate")));
or
Given that
I want ... to get [the] Date(1440959400000+0530) part,
I would use
String value = "/Date(1440959400000+0530)/";
int pos1 = value.indexOf("Date(");
if (pos1 > -1) {
int pos2 = value.indexOf(")", pos1);
if (pos2 > pos1) {
value = value.substring(pos1, pos2 + 1);
System.out.println(value);
}
}
Output is
Date(1440959400000+0530)
Note: This works by looking for "Date(" and then the next ")", and it removes everything not between those two patterns.
If you have specific character, ( and ), use substring method to get the value.
String value = "\\/Date(1440959400000+0530)\\/";
int start = value.indexOf("(");
int last = value.lastIndexOf("0");
value = value.substring(start + 1, last + 1);
System.out.println(value); <--- 1440959400000+0530
DataUtil.getDateForUnixDate(value);
I don't know DataUtil.getDateForUnixDate() method, but take care of + character because of it is not number string.
Update
To remove / character use replace method.
String value = "/Date(1440959400000+0530)/";
value = value.replace("/", "");
System.out.println(value);
output
Date(1440959400000+0530)
Mac,
As you asked for something like
String ValueDate = "\/Date(1440959400000+0530)\/";
The above one is not possible in java string, As it shows as invalid escape sequence, So replace the slash '\' as double slash '\' as below,
String ValueDate = "\\/Date(1440959400000+0530)\\/";
If am not clear of our question, pls describe it clearly
Regards,
Hari
i found the answer for my own question.
historyJson.getString("ValueDate");
this return the String like /Date(1440959400000+0530)/
now i can split it. thank you all for the help.
regards, macdaddy

Java - How to split (+ sign) on Strings so it could be read as a Variable/Int?

This question is rather difficult to confer, for simplistic sake:
I am loading some Strings via XML (XStream).
for example, Your total count is +variable+ .
The outcome would be
"Your total count is +variable+ ."
when it ideally should be
"Your total count is" + variable + "." aka "Your total count is 1."
The issue: (if you can't see it) it reads the variable as if it were a String.
I know I would need to split that String from where the plus sign starts and ends and then connect it to the String, for it to read as a variable, like the above. But how? I need this to be done so that the String before the variable and after it is split.
so:
"Your total count is 50, would you like a cookie?"
aka
"Your total count is " + variable + " , would you like a cookie?"
Thank you alot!
Okay, I agree it's very confusing. I've edited this post (read below).
Well I am loading some Strings via XML this could be the same case if I were loading them via a .txt or a config file.
On the XML file, I lay it out like so:
<list>
<dialogue>
<line>
<string> Your total count is + Somewhere.totalCount +, Would you like a cookie?</string>
</line>
</dialogue>
</list>
As you can see, the XML file can't locate where the variable (in a class is), nor can it recognise if it is a variable or a string.
I know that I would need to alter the way it reads it, so if there is a plus sign (+) anywhere on the String, it would simply "split" it away from the original String so I can reconnect it.
E.g. Your phone number is + PhoneBook.phoneNumber + should I call you? as it would be read from a XML file.
I want to "split" the String from front to back like so:
"Your phone number is " + PhoneBook.phoneNumber + " should I call you?"
At the same time, I'm not assigning a variable because It's already declared in the XML file, I want it to recognise it as a int.
First, Java can not know that the +variable+ part of your string should be replaced with the value of the corresponding variable and also does not provide some "eval" like functionality like PHP or other scripting languages do, which might help you with that.
If you want to exactly replace this specific '+variable+' part of the string, it can be done like this:
int variable = 1;
String text = "Your total count is +variable+.";
String textWithVariableValue = text.replaceAll("\\+variable\\+", Integer.toString(variable));
But if you want to replace variables with arbitrary names, you will have to put them into a Map first, and then find all occurences of +somename+ in the string and replace it with the corresponding value stored in the map. Something like this:
Map<String, Object> variables = new HashMap<String, Object>();
variables.put("var1", 1);
variables.put("foo", 5);
String text = "var1 = +var1+, foo = +foo+";
String textWithVariableValues = text;
for (String variableName : variables.keySet()) {
Object variableValue = variables.get(variableName);
textWithVariableValues = textWithVariableValues.replaceAll("\\+" + variableName + "\\+", variableValue.toString());
}
Sounds like what you need is the
String.format() method:
int total = calculateTotal();
String s = String.format("Your total is %1d.", total);
Not split, but find and replace.
Simplistically,
int variable = 1;
String src = "Your total count is +variable+.";
String result = src.replaceAll("\\+variable\\+.", Integer.toString(variable));
System.out.println(result);
Should print "Your total count is 1."
EDIT: (after your comment) If you need to replace a multiple variables in one go then the following works for me:
// Replace the ff. with the actual map of variables & values
Map<String, String> vars = Collections.singletonMap(
"variable", Integer.toString(123));
String src = "Your total count is +variable+.";
Pattern p = Pattern.compile("\\+(\\w+)\\+");
StringBuffer sb = new StringBuffer();
Matcher m = p.matcher(src);
while (m.find()) {
String varName = m.group(1);
if (vars.containsKey(varName)) {
m.appendReplacement(sb, vars.get(varName));
}
}
m.appendTail(sb);
System.out.println(sb.toString());
Prints "Your total count is 123."

Categories