I was optimizing an application and wanted to change my for loops to enhanced loops:
From:
for (int m = 1;m < MAX_BEREN;m++)
{
Wasberen[m] = new Wasbeer();
Wasberen[m].YYY = r.nextInt(SchermY - 28);
}
to:
for (Wasbeer a : Wasberen)
{
if (a!=null)
{
a = new Wasbeer();
a.YYY = r.nextInt(SchermY - 28);
}
}
I get a NullPointerException, because it probably doesnt know how much 'beren' can be in
the array, but I'm not sure how to manage the same as the loop above (MAX_BEREN = 11).
If the array reference ('Wasberen' in this case) in an enhanced for statement is null, then a NullPointerException will result when the statement is executed.
For initializing arrays, you should stick to the syntax you had before.
You can't use the enhanced for-loop in Java to fill an array. (I'm assuming your Wasberen array was already created before - if not, this will get you a NullPointerException in both variants.)
Your code (simplified)
for (Wasbeer a : Wasberen)
{
a = ...;
}
is equivalent to
for (int i = 0; i < Wasberen.length; i++)
{
Wasbeer a = Wasberen[i];
a = ...;
}
This assignment will change the local variable a, but will have no effect on the contents of the array.
Related
protected Day[] days= new Day[n];
for(int i=0;i<days.length; i++)
{
days[i]= new Day(5);
}
Above mentioned code works fine for me but modified for loop as mentioned below results in NullPointerException when I try to access the elements of the array. Can anyone explain why does it happens?
protected Day[] days= new Day[n];
for(Day d:days)
{
d= new Day(5);
}
When Java sees the enhanced for loop that you've made, it runs whatever you put inside it and makes a new variable (called d) and gives this variable a value of whatever is inside of your array. When you set d equal to a new Day(5); you are changing the value of the variable d, not the value inside the array. Here is a workaround:
protected D[] days = new Day [n];
for(int i = 0;i<days.length;i++)
days[i] = new Day(5);
This reaches into the actual array to set values. Hope this helps!
Loop variable in enhanced for loop is temporary. Assigning it inside loop body has no effect on the original item. Here is what happens to the loop according to Java Language Specification:
Day[] days = ...
for (int i = 0; i < days.length; i++) {
Day d = days[i];
...
}
When you assign d, it changes the local variable d, not days[i], which isnearly always an error. For that reason, some programming shops adopt a practice of making loop variable of enhanced for loop final:
for(final Day d:days) {
d= new Day(5); // <<== Compile-time error
}
If you want to shorten the code by avoiding the loop, use
Arrays.setAll(days, i -> new Day(5));
Second type of for uses Iterator for iterating by elements. Initializing reference d makes no sence, because this operation doesn't change reference inside your array.
I try to have this enhanced for loop of a Java code in my C# code:
for (float value : array) {
if (Float.isInfinite(value) || Float.isNaN(value)) {
value = 0;
}
}
I tried this out:
foreach (float value in array)
{
if (float.IsInfinity(value) || float.IsNaN(value))
{
value = 0;
}
}
But I have this error that told me I have not the right to modify value because it is an iteration variable.
You need to use a normal for loop if you want to update the iterator variable:
for(int i = 0 ; i < array.Length; i++)
{
if (float.IsInfinity(array[i]) || float.IsNaN(array[i]))
{
array[i] = 0;
}
}
From C# specifications:
The iteration variable corresponds to a read-only local variable with
a scope that extends over the embedded statement. During execution of
a foreach statement, the iteration variable represents the collection
element for which an iteration is currently being performed. A
compile-time error occurs if the embedded statement attempts to modify
the iteration variable (via assignment or the ++ and -- operators) or
pass the iteration variable as a ref or out parameter.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
This is the following code. I have to make the array null for a purpose, then when I initialize the array components to 1, it shows null pointer exception. How to handle this?
public static void main(String[] args) {
double[] a;
a=null;
if(a==null)
for(int i=0;i<12;i++)
a[i]=1;
}
You need to create an array object and assign it to the array variable before trying to use the variable. Otherwise you are creating the very definition of a NullPointerException/NPE: trying to use (dereference) a reference variable that refers to null.
// constant to avoid "magic" numbers
private static final int MAX_A = 12;
// elsewhere in code
if (a == null) {
a = new double[MAX_A]; // you need this!
for (int i = 0; i < a.length; i++) {
a[i] = 1.0;
}
}
a[i]=1 // That's the problem.
You are trying to assign a value, without actually allocating memory (aka, not initializing). Indirectly you are trying to invoke a operation on NULL object which obviously results in Null Pointer Exception.
So
if(a == null){
a = new double[12];
//other for loop logic
}
will solve the problem. 12 is the size of the array (The number of double value it can hold/store).
You have to create the array before initialization -
double[] a;
a=null;
if(a==null){
a = new double[12];
for (int i = 0; i < a.length; i++) {
a[i] = 1.0;
}
}
Since double array a is null when you are trying to access the array element like this -
a[i]=0;
It produces NullPointerException.
At the first place why don't you make it NULL while declaring the variable double[] a = null;
The reason why you are getting NullPointer is because you are trying to access it when it is NULL a[i]=1;. This is as good as String name = null; name.toString(); You are doing some operation on an NULL value so getting NullPointer.
Just initialize it and then try to access it and you will not get NullPointer. This is like you should first allocate some memory and then try to access the memory location, when no memory is allocated, you will get NullPointer which tells you that there is no memory allocated yet. Hope this helps.
I don't understand why this works and I hope somebody can explain it to me.
Here is an example:
TestObject array[] = new TestObject[10];
for(int i= 0; i <= 10; i++){
TestObject object = new TestObject();
object.setValue(i);
array[i] = object;
System.out.println(array[i].getObject());
}
Why can I create multiple instances of "TestObject" with the same name in the loop?
Usually you can't create instances with the same name:
TestObject o = new TestObject(1);
TestObject o = new TestObject(2);
Well, this will obviously throws an error...
The scope for a for loop is limited to the iteration. So TestObject object is created and destroyed in each iteration.
Every iteration of a loop is a block and, as a block, has its own scope. You can achieve the same result by doing this:
{
int i = 0;
}
{
int i = 1;
}
// etc
This is because 'object' is in visibility scope of current loop iteration, so for next iteration, there can be initialized a new one with the same name (other scope).
it's the scope of object problem. every iteration has its scope let's say they are not the same object at all
I don't understand why this is giving me a null pointer exception when I try to add a value to the a1[i] array.
public class Array {
String text;
int total = 0, count = 0;
Array[] a1 = new Array[100];
Scanner scan = new Scanner(System.in);
public void setData() {
int i=0;
System.out.println(a1.length);
do {
System.out.println("Enter some data: ");
text = scan.next();
if (text.equals("end"))break;
a1[i].text = text; //I get a null pointer exception here. Not sure why.
i++;
} while (true);
}
Everything initialized in the a1 array is null. You'd have to put a new instance of Array() in there before doing anything with the member methods.
What this translates to: Every time you want to do something with a1[i], you'd have to have a new instance of Array in there first.
Example:
for(int i = 0; i < n; i++) {
a1[i] = new Array();
}
Because there isn't an object stored at a1[i]. What you're essentially saying at that line is:
null.text = text
which will break every time
You are getting a null-pointer exception, because you have allocated the space for 100 array elements, but you still need to initialize them:
So before accessing a1[i].text you need to initialize it by calling a1[i] = new Array()
Also I am quite sure, that you actually wanted to create some other kind of object, not Array. Array the class you are currently writing, as I understand, so you probably want to have multiple Strings, e.g. String[].
I recommend to you to use a LinkedList instead.
Array[] a1 = new Array[100]; //here you just create an array of references to objects which are set to null
a1[i].text = text; //before this line you should assign to a1[i] a reference to Array object for example a1[i] = new Array();