Java Can not Cast from String to Integer_Sovled - java

HashMap<String, String> config = Feeds.config;
String num = config.get("NumOfFeeds");
System.out.println(num);
feedsAmount = ((Integer)num).intValue();
System.out.println(feedsAmount);
I've also tried Integer.parseInt(num) and Integer.decode(num) and Integer.valueof(bu)
Results as follows: 40
Exception in thread "main" java.lang.NumberFormatException: For input string:"40"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:458)
at java.lang.Integer.parseInt(Integer.java:499)
at fetch_RSS.<init>(fetch_RSS.java:40)
at testing.main(testing.java:27)
The problem was caused by different encoding from the txt file I'm reading from and the encoding in Elipse which is the macRoman by default.

The correct way of working is this:
String num = config.get("NumOfFeeds");
int feeds = Integer.parseInt(num);
This, only when you are sure that the String is representing a number the valid way.
-30 // correct
0 // correct
2000 // correct
"40" // invalid
40 // valid
2.000 // invalid
2.000.000 // invalid
20,0 // invalid
2,000,000 // invalid

Your exception got raised in Integer.java:458.
Looking into the source code of Integer I see that some characters of your String "40" returned a negative value (most probably -1) for Character.digit(s.charAt(i++), radix) where i is iterating over String's characters and radix is 10.
This should not happen normally. But it happens when the String is "4o" and not "40" like #Løkling's wild guess in the comments.
You should debug here to see what really happens.

Of course you can't cast from String to Integer. A String is not a Integer, and Integer is not a String.
You have to use int i = Integer.parseInt(..). It works if the string is a properly formatted integer.

For a cast to succeed in Java, the reference being cast must point to an object that is actually an instance of the type being cast to. A reference to String can't be cast to Integer because an object couldn't possibly be both things.
(This is somewhat unlike a cast in C, which is basically just saying, reinterpret the data stored here according to a different datatype. It would still be incorrect in C to use casting as a method to convert a string representing a number to a numeric value.)
Integer.parseInt is what you are looking for here. What problem are you having with it?

Remember : In java, we can only cast between objects if they are EXPLICITLY of the same type ! In other languages , like python, we can do the casting you requested here, because those languages allow "duck typing".
You must use Integer.parseInt("1234"), to create an Integer object from a String.
Alternatively you could create an Object wrapper to your data :
class MyObject
{
Object input;
public MyObject(Object input)
{
this.input=input;
}
public Integer getInt()
{
return Integer.parseInt(input.toString());
}
public String getString()
{
return input.toString();
}
}
This would be overkill for your simple problem, however :)

Related

Error in Math.random() for arrayList

I'm sure this is a small, stupid error that I just can't see.
I'm getting a compiling error in this code:
private String setQuestions(){
int match = Math.floor(Math.random()*cities.length); }
in my length.
Compiling error is:
"Cannot find symbol
symbol: variable length
location: variable cities of type ArrrayList "
How can I fix this? I do want to use Math.random();
Also not sure if this makes a difference, but this is is being done within a String method.
Thanks in advance!
if cities is of type ArrayList you have to use cities.size() instead of cities.length.
There are a couple of errors here.
First: If your method is not void is because you're gonna return something, in your method you should return a String.
Second: The result of Math.floor(Math.random()*cities.length) it's a double, so you can't store on a simple int, you should parse it or just change the int for double
Third: If you wanna return that match variable you should parse it to a String like you're declaring or just change the declaration to double.
So, the easier fix would be just changing the string and int for double and return it like this:
private static double setQuestions(){
double match = Math.floor(Math.random()*cities.length);
return match;
}
Remember if you want to use the double returned you should store it when you call it, like this:
double result = setQuestions();
Hope it helps!
The code has three problems:
First, the variable "cities" is an ArrayList, as the compiller error wrote. ArrayList is a Collection which implements the interface List. The size of any implementations of List is accessable by method size(). Than, you should change cities.length by cities.size() or you turn cities as array.
Second, you defined the variable "match" as an int value but method floor from Math return a double. If you really want "match" to be a int, than you can use the cast against the method floor, that is, you code become: int match = (int) Math.random()*cities.size();
Third, your method requires an String as return, than you should return the String object correctly.

Wrappers in Java

public class Test {
public static void main(String[] args) {
Integer obj1 = Integer.valueOf(12);
Integer obj2 = Integer.valueOf("12");
System.out.println(obj1.intValue() + " " + obj2.intValue());
Integer obj3 = Integer.valueOf("1010", 2);
Integer obj4 = Integer.valueOf(1010, 2);//Compile time error.
}
}
//As valueOf() method takes both String and the repective type as argument, but then why
does last statement shows Compile time error where I am trying to use valueOf() method with radix.
Because there is no such overload. Read the documentation.
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html
Albeit a good question,I don't know why your question was downvoted,it might be so because your comment was not seen by most of them!
The first part is indeed correct as answered by Jeroen Vannevel,there is no such overloaded version of Integer.valueOf() available in java-library!
The java.lang.Integer.valueOf(String s, int radix) method returns an Integer object holding the value extracted from the specified String s when parsed with the radix given by the second argument radix. So,here String is parsed into Integer object!!!
On the other hand,you are talking about Integer.valueOf(1010, 2). The number 1010 is already an Integer and so it can't be parsed again back to Integer! Also,if you want BinaryString---simply use java.lang.Integer.toBinaryString(). For your satisfaction,if you are still thinking of parsing,then proceed below :-
The solution to end your doubt is
how will you convert Integer.valueOf(1010,16) again into Integer
object???? It'll be containing String(hexadecimal representation of 3F2---see F here)!!!
I hope you have got the reason!!!
Hence,this was not provided in the java-library.

Conversion of Generic Integer type to Character type

My question is about the topic of casting Generic Java types. Suppose we have an Integer ArrayList like so:
List<Integer> intFileContents = new ArrayList<Integer>(8192);
Now, I want to retrieve one Integer from the list, and then print it out as a character, since the ArrayList actually reads characters from a text file:
while ((fileBuffer = stream.read())!= -1) {
intFileContents.add(fileBuffer);
System.out.print(fileBuffer);
}
If I was using primitive types, I'd just cast it like this:
char someChar = (char)someInt;
However, casting Generic types (Character)intFileContents.get(pos); is impossible, since they are objects. Now, there is a method in the Integer class: Integer.toString(), which should return said Integer as a string. Unfortunately, all it does is, if we f.e. had and Integer = 255, the String would be "255". That is not what I want, since casting primitive ints to chars gives a character of the correct ASCII code, so f.e. casting (char)65 would return someChar = 'A'. This is exactly what I want to get, except with Generic types. What is the way to achieve this?
There are a few options here. One thing you can do is get the integer value, then cast/print that:
(char) intFileContents.get(pos).intValue(); // Do something with this
Probably a better option would be to convert the int values you read in immediately, like this:
List<Character> charFileContents = new ArrayList<Character>(8192);
while ((fileBuffer = stream.read())!= -1) {
charFileContents.add((char) fileBuffer); // <-- Do the cast before storing the value
System.out.print(fileBuffer);
}
Then, when you go to print the character, it is already the proper type. Be warned that this only works for one specific encoding (don't remember which), so if you want another encoding you'll have to use a InputStreamReader instead of a plain InputStream

Int cannot be cast as String issue at runtime

Running my code results in the following error: java.lang.Integer cannot be cast to java.lang.String
This is what I have:
for(Map<String, Object> record: list) {
if(((String)record.get("level")).equals("1")) {
rootList.add(record);
}
}
I have tried converting that little snippet to an Int using toString but it just gives me a compiling error. I'm new to java (and I did not write this code either) so forgive me if it's a stupid mistake.
Your Maps holds values of type Object, meaning they can really hold anything as values (since everything extends Object); there's no guarantee that a given value will be a String. By your error, it would appear that one of the values in one of your maps is an Integer, which evidently cannot be cast to a String. The quick-fix is to use toString:
record.get("level").toString().equals("1")
But note that this will yield true for any object whose toString returns "1", not just strings. If you want to only check for equality with the string "1", then you can use "1".equals(...), since equals can take any object as an argument.
try
Object number = record.get("level");
if("1".equals(number)){
}
try one of this alternatives:
rootList.add(record + "");
or
rootList.add(new String(record));
Well, if the Map values are Integers, then toString() should work for converting them to strings:
for(Map<String, Object> record: list) {
if(record.get("level").toString().equals("1")) {
rootList.add(record);
}
}

Can an int be null in Java?

Can an int be null in Java?
For example:
int data = check(Node root);
if ( data == null ) {
// do something
} else {
// do something
}
My goal is to write a function which returns an int. Said int is stored in the height of a node, and if the node is not present, it will be null, and I'll need to check that.
I am doing this for homework but this specific part is not part of the homework, it just helps me get through what I am doing.
Thanks for the comments, but it seems very few people have actually read what's under the code, I was asking how else I can accomplish this goal; it was easy to figure out that it doesn't work.
int can't be null, but Integer can. You need to be careful when unboxing null Integers since this can cause a lot of confusion and head scratching!
e.g. this:
int a = object.getA(); // getA returns a null Integer
will give you a NullPointerException, despite object not being null!
To follow up on your question, if you want to indicate the absence of a value, I would investigate java.util.Optional<Integer>
No. Only object references can be null, not primitives.
A great way to find out:
public static void main(String args[]) {
int i = null;
}
Try to compile.
In Java, int is a primitive type and it is not considered an object. Only objects can have a null value. So the answer to your question is no, it can't be null. But it's not that simple, because there are objects that represent most primitive types.
The class Integer represents an int value, but it can hold a null value. Depending on your check method, you could be returning an int or an Integer.
This behavior is different from some more purely object oriented languages like Ruby, where even "primitive" things like ints are considered objects.
Along with all above answer i would like to add this point too.
For primitive types,we have fixed memory size i.e for int we have 4 bytes and char we have 2 bytes. And null is used only for objects because there memory size is not fixed.
So by default we have,
int a=0;
and not
int a=null;
Same with other primitive types and hence null is only used for objects and not for primitive types.
The code won't even compile. Only an fullworthy Object can be null, like Integer. Here's a basic example to show when you can test for null:
Integer data = check(Node root);
if ( data == null ) {
// do something
} else {
// do something
}
On the other hand, if check() is declared to return int, it can never be null and the whole if-else block is then superfluous.
int data = check(Node root);
// do something
Autoboxing problems doesn't apply here as well when check() is declared to return int. If it had returned Integer, then you may risk NullPointerException when assigning it to an int instead of Integer. Assigning it as an Integer and using the if-else block would then indeed have been mandatory.
To learn more about autoboxing, check this Sun guide.
instead of declaring as int i declare it as Integer i then we can do i=null;
Integer i;
i=null;
Integer object would be best. If you must use primitives you can use a value that does not exist in your use case. Negative height does not exist for people, so
public int getHeight(String name){
if(map.containsKey(name)){
return map.get(name);
}else{
return -1;
}
}
No, but int[] can be.
int[] hayhay = null; //: allowed (int[] is reference type)
int hayno = null; //: error (int is primitive type)
//: Message: incompatible types:
//: <null> cannot be converted to int
As #Glen mentioned in a comment, you basically have two ways around this:
use an "out of bound" value. For instance, if "data" can never be negative in normal use, return a negative value to indicate it's invalid.
Use an Integer. Just make sure the "check" method returns an Integer, and you assign it to an Integer not an int. Because if an "int" gets involved along the way, the automatic boxing and unboxing can cause problems.
Check for null in your check() method and return an invalid value such as -1 or zero if null. Then the check would be for that value rather than passing the null along. This would be a normal thing to do in old time 'C'.
Any Primitive data type like int,boolean, or float etc can't store the null(lateral),since java has provided Wrapper class for storing the same like int to Integer,boolean to Boolean.
Eg: Integer i=null;
An int is not null, it may be 0 if not initialized. If you want an integer to be able to be null, you need to use Integer instead of int . primitives don't have null value. default have for an int is 0.
Data Type / Default Value (for fields)
int ------------------ 0
long ---------------- 0L
float ---------------- 0.0f
double ------------- 0.0d
char --------------- '\u0000'
String --------------- null
boolean ------------ false
Since you ask for another way to accomplish your goal, I suggest you use a wrapper class:
new Integer(null);
I'm no expert, but I do believe that the null equivalent for an int is 0.
For example, if you make an int[], each slot contains 0 as opposed to null, unless you set it to something else.
In some situations, this may be of use.

Categories

Resources