Hi everybody. I'm very new to Java as I'm sure you'll be able to tell after you read this post. I am trying to print the first 100 prime numbers using an array. The flowchart I'm using is below followed by the code I have right now. There are many things I'm having a hard time figuring out.
1. How do I give the first slot in the array a value of 1? I thought I did that but it doesn't work.
2. If prime = false how do I tell the array to skip that slot instead of entering a value of 0?
3. Am I doing any of this correctly?
If you create an array of primitives, they will all be initially set to 0. There are a couple of approaches you could take...
1) Keep track of how many primes you have found, and then only check up to that position in the array (an addition condition in your do-while loop, maybe?)
2) Initialize every element of your array to something like "-1". use this as a sentinel and only do the division when the value is NOT equal to -1
3) Don't use an array. You can use an ArrayList, which will grow as you need it to do so. You will probably have to use Integers instead of ints, but that shouldn't be a major change
Also...remember that 1 is NOT prime, and 2 IS prime.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
@Johannes: I'm fairly new to the forum too but I believe that the idea behind the forum is not "you've got a java problem? here is the code that solves it".
It's more like "learn a man to fish and he's got food for the rest of his life".
Hence, try to avoid dropping 'solution code' like that in your answer. The goal is to help the original poster gain insight in Java and learn good practices. See for example the suggestion/advice from fred (ArrayList instead of array etc).
fred rosenberger wrote:Wim is correct. We not only don't want people to provide solutions, we actively delete them (as I have done). Our goal is to teach people to be programmers, and providing an answer does NOT do that.
Thanks to the people that tried to help but after many hours last night I wasn't able to figure it out. I'll get the answer and not many homework points from the teacher later today. I will be so so glad when this class is over.
I need a new interior decorator. This tiny ad just painted every room in my house purple.