I am having trouble getting the random concept down. In my assignment, i have to create a random strings of user determined length and number. I have no problem with the iteration, but when it comes to creating the strings, thats when i don't have a clue. From what i have read from the book and websites i think that it goes something like this:
I'll give you a piece of code: letter = alphabet[r.nextInt(alphabet.length)]
nextInt(x) returns an integer >= 0 and <x
This gives you one random letter.
You can assemble a String from letters using StringBuffer, you can easily make StringBuffers into Strings with a String constructor, and you can put references to your Strings in a String array. [ November 10, 2004: Message edited by: Mike Gershman ]
SCJP 1.4, SCWCD in process
Joined: Nov 10, 2004
I am still having a lot of trouble with Random... when i enter the code snippet that you gave me among with other code. I keep getting null exceptions, or the first letter of my array. I am completely at a loss. Any help would be appreciated.
There are days when any of us would be happy to make one or two lines of code run! What's the simplest thing you can possibly try? Maybe:
just to get a feel for the ints you're going to get.
If you want to use one of those ints to pick a random letter out of the alphabet you'll probably use the int as an index into your array of letters. That's a fine idea, but look at those ints. Some are going to be too big for your array. Read up on Random javadoc to see how to get numbers in the range you want ... 0 through number of letters minus 1.
So try a few more lines:
If you get that going, put it in a for loop to get the right number of letters.
Any of that help?
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Joined: Nov 10, 2004
Okay, i got a little further in my program, now the problem is that i need my for loops to print out strings like:
>> ATTAGACATTACATTAGAAATCCCCCCATACACACA >> what am i doing wrong?
What Joel said.
There's really no need to test for length >= seqArray.length inside the loop. In fact, I don't see a need for the seqArray at all in the code you posted. Also, I would take Mike's suggestion and use a StringBuffer. And you should not be using the "magic number" 4. The argument you pass to nextInt() should be the length of the gene array. I would also break out the inner loop into its own method: