Reputation: 1
I've been trying to polish up on some Java and I'm trying to refresh the basics so I've been working through the Sam's 24 hour java book. One of the projects to familiarize yourself with describing objects gives the code as follows:
package com.java24hours;
public class GremlinLab {
public static void main(String[] arguments) {
int numGremlins = Integer.parseInt(arguments[0]);
if (numGremlins > 0) {
Gremlin[] gremlins = new Gremlin[numGremlins];
for (int i = 0; i < numGremlins; i++) {
gremlins[i] = new Gremlin();
}
System.out.println("There are " + Gremlin.getGremlinCount()
+ " gremlins.");
}
}
}
The error "The array is only written to, never read from" is showing upon compilation in the 7th line:
Gremlin[] gremlins = new Gremlin[numGremlins];
and I can't figure out for the life of me why this is not working! Apologies if I'm being stupid but any help will be greatly appreciated :) Thanks!
Sorry quick edit to add the other class I haven't mentioned!!
I have also got the following class:
package com.java24hours;
public class Gremlin {
static int gremlinCount = 0;
public Gremlin() {
gremlinCount++;
}
static int getGremlinCount() {
return gremlinCount;
}
}
I then specified the command-line arguments by customizing the project configuration.
Last Edit!!... Thanks very much everyone, I really appreciate it. I'm using an IDE and moved the classes to the source packages folder rather than the 'com.java24hours' package....and my original codes have worked fine?! Clearly I'm very much a novice! Thanks again all :)
Upvotes: 0
Views: 3792
Reputation: 83517
This is a warning, not an error. You can safely ignore it and your program will function as you intend.
The warning is because you are creating an array and filling it with elements. But then you never actually use the array nor the elements of that array for anything. For example, you could do
System.out.println("There are " + gremlins.length + " gremlins.");
to print the length of the array. This will remove the warning.
Better yet, if you are writing this as an exercise to learn about static
methods and variables, just don't use an array at all.
Upvotes: 3
Reputation: 424973
You are not doing anything with the elements of the gremlins
array. ie nowhere does your code do something like gremlins[i].someMethod()
, but it's only a warning.
Upvotes: 0