Jonerhan
Jonerhan

Reputation: 97

Java: Creating a String of length X with random chars

The Problem I have to do is as follows

public static String randomDNAString(int dnaLength) /** * @param dnaLength a non-negative int * @return a random String of length dnaLength comprised of the four chars A, T, G, and C */

I thought I did it correctly (though incredibly inefficiently) but it doesn't return anything. Here's my code. Any help is appreciated.

    public static String randomDNAString(int dnaLength){
    Random rand = new Random();
    char[] dna;
    dna = new char[dnaLength];
    for(int i = 0; i<dnaLength;i++){
        int tempC = rand.nextInt(4);
        if(tempC == 0)
            dna[i] = 'A';
        if(tempC == 1)
            dna[i] = 'G';
        if(tempC == 2)
            dna[i] = 'C';
        if(tempC == 3)
            dna[i] = 'T';

    }
    return (java.util.Arrays.toString(dna));
}

Upvotes: 1

Views: 1359

Answers (3)

Jonerhan
Jonerhan

Reputation: 97

There's nothing wrong with this. I'm just dumb and when I called it in the main I used

randomDNAString(20);

instead of

System.out.println(randomDNAString(20));

Thanks for your help everyone, I'm just dumb sometimes

Upvotes: 0

arshajii
arshajii

Reputation: 129517

The other answer's suggestion using of using StringBuilder was a good one. However, you can make this even simpler:

public static String randomDNAString(int dnaLength) {
    Random rand = new Random();
    StringBuilder dna = new StringBuilder(dnaLength);

    for (int i = 0; i < dnaLength; i++) {
        dna.append("ACGT".charAt(rand.nextInt(4)));
    }

    return dna.toString();
}

Upvotes: 2

Anubian Noob
Anubian Noob

Reputation: 13596

We can improve on your answer by changing the if chain to a switch statement and using a StringBuilder.

public static String randomDNAString(int dnaLength) {
    Random rand = new Random();
    StringBuilder dna = new StringBuilder();
    for(int i=0;i<dnaLength;i++) {
        switch(rand.nextInt(4)) {
            case 0:
                dna.append("A");
                break;
            case 1:
                dna.append("C");
                break;
            case 2:
                dna.append("G");
                break;
            case 3:
                dna.append("T");
                break;
        }
    }
    return dna.toString();
}

To print the output, try:

System.out.println(randomDNAString(10));

Upvotes: 0

Related Questions