-2

I'm supposed to fill this array of string with all the letters from the alphabet ex: "a","b","c","d", etc.

I've been staring at this for an hour and I confused on where to start? I was just introduced to arrays today in class so excuse my ignorance . Usually isn't an array filled like this String[] randomA = {'a','b','c'} etc. So I'm confused on how to fill it with a loop. Can someone tell me why they start with for ( char ch = ) in the for loop and point me in the right direction on how to start?

import java.util.Arrays;

public class Fill
{
   public static void main(String[] args)
   {
      String[] letters = new String[26];
      for (char ch = . . .; . . .; . . .)
      {
         letters[. . .] = . . .;
      }
      System.out.println(Arrays.toString(letters));
   }
}
Vickie
  • 67
  • 3
  • 9
  • 1
    Hint: the `char` type in Java is an integer type. If you start with `'a'` and add 1, you get the next letter (`'b'`). – Ted Hopp Jul 18 '17 at 02:19
  • Check this question: https://stackoverflow.com/questions/11671908/can-the-char-type-be-categorized-as-an-integer You can increment char type. Each letter corresponds to a unique value from ASCII Table that represents only that letter. Check it too: https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html – Turkhan Badalov Jul 18 '17 at 02:22
  • The "..." in your template _are_ pointers to where to start. Read about [the syntax of a `for` loop](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html). Read about [how to access array elements](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html). – Solomon Slow Jul 18 '17 at 06:04

3 Answers3

1

Try this.

String[] letters = IntStream.rangeClosed('a', 'z')
    .mapToObj(c -> String.valueOf((char)c))
    .toArray(String[]::new);
1

char types are actually just numbers which have character representations according to Unicode. You can increment, decrement, and do basic math with them.

Here's one way you could write it:

import java.util.Arrays;

public class Fill
{
   public static void main(String[] args)
   {
      String[] letters = new String[26];
      for (char ch = 'a'; ch <= 'z'; ch++)
      {
         letters[ch - 'a'] = String.valueOf(ch);
      }
      System.out.println(Arrays.toString(letters));
   }
}
4castle
  • 32,613
  • 11
  • 69
  • 106
1

Try this.

String[] letters = new String[26];
for (int i = 0; i < 26; i++) {
    letters[i] =  (char)('a' + i) + "";
}
System.out.println(Arrays.toString(letters));