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.
Use the typeof operator to check if a variable is defined or initialized, e.g. if (typeof a !== 'undefined') {} . If the the typeof operator doesn't return a string of "undefined" , then the variable is defined.
There is no way in the C++ language to check whether a variable is initialized or not (although class types with constructors will be initialized automatically). Instead, what you need to do is provide constructor(s) that initialize your class to a valid state.
For a field variable you can check by comparing the int to 0 that is the default value for an int field : private int x: // default 0 for an int ... public void foo(){ if (x == 0){ // valid check // ... } }
The typeof operator will check whether a variable is defined or not. The typeof operator doesn't throw a ReferenceError exception when it is used with an undeclared variable. The typeof null will return an object. So, check for null also.
You can't cast a String
to an int
. Java is strongly typed, and there is no implicit type conversion like you might find in a scripting language.
To convert a String
to an int
, use an explicit conversion, like Integer.parseInt(String)
.
All member variables and elements of arrays are initialized with a default value. For int
types, the value is 0. For reference types (any subtype of Object
), the default value is null
. 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:
int[] n = new int[Integer.parseInt(s[0]);
for (int idx = 0; idx < n; ++idx)
n[idx] = Integer.parseInt(s[idx + 1]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With