-2

How can I create an 80-character string array with the letters a, b, and c? Each time, the places of these letters a, b and c need to be arranged randomly. For example abcbabcabcababbc ... abcba

 String[] str = new String[80];
  • see https://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string for different approaches to creating a string with random characters – Sebastian Richner Jan 09 '21 at 14:32
  • Loop over the array positions, get a random number 0-2, then put the appropriate character in that index – OneCricketeer Jan 09 '21 at 14:41

1 Answers1

1

You could use the Ascii values. Lower case letters start with 97 (a).

public static void main(String[] args) {
    Random r = new Random();
    String[] s = new String[80];
    for (int i = 0; i < 80; ++i) {
        s[i] = "" + ((char) (r.nextInt(3) + 97));
    }

    Arrays.stream(s).forEach(System.out::print);
}

Alternative solution:

public static void main(String[] args) {
    Random r = new Random();
    String[] letters = {"a", "b", "c"};
    String[] s = new String[80];
    for (int i = 0; i < 80; ++i) {
        s[i] = letters[r.nextInt(letters.length)];
    }

    Arrays.stream(s).forEach(System.out::print);
}
DarkMatter
  • 1,007
  • 7
  • 13