First of all, I’m fairly new to Java, so sorry if this question is utterly simple.
The thing is: I have a String[] s made by splitting a String in which every item is a number. I want to cast the items of s into a int[] n.
s[0] contains the number of items that n will hold, effectively s.length-1. I’m trying to do this using a foreach loop:
int[] n;
for(String num: s){
//if(n is not initialized){
n = new int[(int) num];
continue;
}
n[n.length] = (int) num;
}
Now, I realize that I could use something like this:
int[] n = new int[(int) s[0]];
for(int i=1; i < s.length; i++){
n[i-1] = (int) s[i];
}
But I’m sure that I will be faced with that “if n is not initialized initialize it” problem in the future.
You can’t cast a
Stringto anint. Java is strongly typed, and there is no implicit type conversion like you might find in a scripting language.To convert a
Stringto anint, use an explicit conversion, likeInteger.parseInt(String).All member variables and elements of arrays are initialized with a default value. For
inttypes, the value is 0. For reference types (any subtype ofObject), the default value isnull. Local variables don’t get a default value, but the compiler analyzes the code to ensure that a value is assigned before the variable is read. If not, the code will not compile.I think what you want is something like this: