ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
As far as I am aware you need to use a loop in Java, but I think that your code will miss the last two elements of the array, you could try the following
Code:
int limit = Integer.parseInt(args[0]);
int start = Integer.parseInt(args[1]);
double[] list = new double[limit];
for (int i = 0; i < limit; i++) {
list[i] = i+start;
}
Thanks for the reply graemef, however I don't need the user to specify a starting point - the starting value is fixed at 2 (which is assigned to list[0]).
in your original code j starts out 2 behind i. when i reaches limit (which is also the size of the array) j is still 2 behind i. loop stops and the last 2 in array are left unset.
15 int limit = Integer.parseInt(args[0]);
16 int start = 2;
17
18 int numbers[] = new int[limit];
19
20 for (int i = 0; i < limit; i++) numbers[i] = i + start;
The code compiles without a complaint, however I get an error when I try to run it:
Code:
Exception in thread "main" java.lang.NullPointerException
at Eratosthenes.main(Eratosthenes.java:20)
What gives?
EDIT: Also, is there a way to create arrays with unspecified (because they're unknown) lengths? (ie. Perl reference again - lists/arrays just exist with variable lengths).
> Also, is there a way to create arrays with unspecified (because they're unknown) lengths? (ie. Perl reference again - lists/arrays just exist with variable lengths).
yes, use an ArrayList or other container.
Code:
18 int numbers[] = new int[limit];
19
20 for (int i = 0; i < limit; i++) list[i] = i + start;
you are creating an array named numbers then using array called list.. is that what you intended?
im not understanding you completely. are you still getting the exception? if you are the only thing that i can see that would be causing it is the args that the program is receiving.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.