Question

How do I take a random char element from an existing array and assign it to...

How do I take a random char element from an existing array and assign it to a new array? I have this code with a testing method but my code only returns an empty array instead of the chars expected.

public static char[] generateHiddenCode(Random rand, int numPositions, char[] symbols) {

char[] arrCode = new char[numPositions];

for (int i=0; i<arrCode.length; ++i) {

arrCode[i] = (char) rand.nextInt(symbols.length); }

return arrCode; }

Test:

   private static void testGenerateHiddenCode() {

boolean error = false;

{ //"randomly" chooses 3 symbols from the list

//We know which 3 will be chosen since we set the seed

Random rand = new Random(123);

int numPositions = 3;

char [] symbols = {'A', 'B', 'C', 'D'};

char [] expected = {'C', 'A', 'D'};

char [] result = MasterMind.generateHiddenCode( rand, numPositions, symbols);

if ( !Arrays.equals( expected, result)) {

System.out.println("1) testGenerateHiddenCode expected: " + Arrays.toString(expected) + " result: " + Arrays.toString(result));

error = true;

}

}

if (error) {

System.out.println("testGenerateHiddenCode failed");

} else {

System.out.println("testGenerateHiddenCode passed");

}

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

There is only one change in generateHiddenCode() method everything else is correct, you were generating a number using rand and casting to char but you are supposed to generate a number from rand and get the character in symbol array present at generated index -

public static char[] generateHiddenCode(Random rand, int numPositions, char[] symbols) {

       char[] arrCode = new char[numPositions];

       for (int i = 0; i < arrCode.length; ++i) {
           // get char from symbol array and assign to arrCode array
           arrCode[i] = symbols[ rand.nextInt(symbols.length)];
       }
       return arrCode;
   }

Add a comment
Know the answer?
Add Answer to:
How do I take a random char element from an existing array and assign it to...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • JAVA HELP: Directions Write a program that will create an array of random numbers and output...

    JAVA HELP: Directions Write a program that will create an array of random numbers and output the values. Then output the values in the array backwards. Here is my code, I am having a problem with the second method. import java.util.Scanner; import java.util.Random; public class ArrayBackwards { public static void main(String[] args) { genrate(); print(); } public static void generate() { Scanner scanner = new Scanner(System.in);    System.out.println("Seed:"); int seed = scanner.nextInt();    System.out.println("Length"); int length = scanner.nextInt(); Random random...

  • I am currently doing homework for my java class and i am getting an error in...

    I am currently doing homework for my java class and i am getting an error in my code. import java.util.Scanner; import java.util.Random; public class contact {       public static void main(String[] args) {        Random Rand = new Random();        Scanner sc = new Scanner(System.in);        System.out.println("welcome to the contact application");        System.out.println();               int die1;        int die2;        int Total;               String choice = "y";...

  • Here is the indexOf method that I wrote: public static int indexOf(char[] arr, char ch) {...

    Here is the indexOf method that I wrote: public static int indexOf(char[] arr, char ch) {            if(arr == null || arr.length == 0) {                return -1;            }            for (int i = 0; i < arr.length; i++) {                if(arr[i] == ch) {                    return i;                }            }        return -1;       ...

  • I'm writing this class called CharArrayProject_3 that removes repeating elements from an array of chars. However,...

    I'm writing this class called CharArrayProject_3 that removes repeating elements from an array of chars. However, when I run the driver class, it just outputs two sets of dashed lines. What am I getting wrong? Is it the deleteRepeats() method?: public class CharArrayProject_3 { private char[] array; privateint length; privateintnumberOfRepeats; public CharArrayProject_3( char[] arr ) { length = arr.length; array = new char[ length ]; numberOfRepeats = 0; for( int k = 0; k < arr.length; k++ ) { array[k]...

  • I need help making this work correctly. I'm trying to do an array but it is...

    I need help making this work correctly. I'm trying to do an array but it is drawing from a safeInput class that I am supposed to use from a previous lab. The safeInput class is located at the bottom of this question I'm stuck and it is not printing the output correctly. The three parts I think I am having most trouble with are in Bold below. Thanks in advance. Here are the parameters: Create a netbeans project called ArrayStuff...

  • Need help with this binary tree program. I will give a thumbs up for anybody who...

    Need help with this binary tree program. I will give a thumbs up for anybody who helps. Source Code: import java.util.Random; import java.util.Scanner; import java.util.Arrays; import java.util.Collections; import java.util.ArrayList; public class Trees { public static int[] prepareData(int[] data){ /* Data is prepared by inserting random values between 1 and data.length. Data items may be assumed to be unique. Please refer to lab spec for the problem definiton. */ ArrayList list = new ArrayList(); for (int i=0; i< data.length; i++) {...

  • MUST BE PROCEDURAL CODE, DO NOT USE GLOBAL VARIABLES. Write a program in C++that generates random...

    MUST BE PROCEDURAL CODE, DO NOT USE GLOBAL VARIABLES. Write a program in C++that generates random words from a training set as explained in the lectures on graphs. Do not hard-code the training set! Read it from a file. A suggested format for the input file: 6 a e m r s t 10 ate eat mate meet rate seat stream tame team tear Here are some suggestions for constants, array declarations, and helper functions #include <iostream> #include <fstream> #include...

  • I would really like to find another way to do this program Random rand = new...

    I would really like to find another way to do this program Random rand = new Random(); String choice = null; boolean valid = false; int a = rand.nextInt(10); int b = rand.nextInt(10); int c = rand.nextInt(10); int d = rand.nextInt(10); while (!valid) { // do{ // if (a == b) { rand.nextInt(10); } if (a == c) { rand.nextInt(10); } if (a == d) { rand.nextInt(10); } if (b == c) { rand.nextInt(10); } if (b == d) {...

  • IVOVI U UL Question 46 Suppose we have Random rand = new Random(); Which of the...

    IVOVI U UL Question 46 Suppose we have Random rand = new Random(); Which of the following expression generates a random integer between 20 and 100, inclusive? rand.nextint() 96 80 rand.nextint() 96 80 + 20 rand.nextInt() % 81 rand.nextInt() % 81 + 20 A Moving to another question will save this response. Moving to another question will save this response. Question 47 Suppose I have the following Scanner object: File file = new File("data txt") Scanner input = new Scanner(file);...

  • The following code skeleton contains a number of uncompleted methods. With a partner, work to complete...

    The following code skeleton contains a number of uncompleted methods. With a partner, work to complete the method implementations so that the main method runs correctly: /** * DESCRIPTION OF PROGRAM HERE * @author YOUR NAME HERE * @author PARTNER NAME HERE * @version DATE HERE * */ import java.util.Arrays; import java.util.Random; import java.util.Scanner; public class ArrayExercises { /** * Given a random number generator and a length, create a new array of that * length and fill it from...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT