Seiji
Seiji

Reputation: 31

Java- Putting alphabet into an array with for loops

I'm trying to add a letter to each slot in the arr[] with for loops, but the output displays only the letter 'a' several times. How can I fix this?

public class Bananas {

public static void main(String[] args) {
    char[] arr = new char[26];
    int j = 0;
    for (char i = 'a' ; i <= 'z' ; i++) {
        while (j < arr.length){
            arr[j] = i;
            j++;
        }
    }
    for (int k = 0; k < arr.length; k++) {
        System.out.println(arr[k]);
    }
  }
}

Upvotes: 0

Views: 3923

Answers (1)

Paul Boddington
Paul Boddington

Reputation: 37645

You only need one loop. This should do it.

public static void main(String[] args) {
    char[] arr = new char[26];
    int j = 0;
    for (char i = 'a' ; i <= 'z' ; i++) {
        arr[j] = i;
        j++;
    }
    for (int k = 0; k < arr.length; k++) {
        System.out.println(arr[k]);
    }
}

Upvotes: 2

Related Questions