Kale Joe
Kale Joe

Reputation: 163

How to create an array of integers in char type?

I am trying to create an array of integers in char type for a given dimension. For instance if the dimension is 5 the array should be {'1', '2', '3', '4', '5'}, however I am not getting any output.

public static void main(String[] args) {
    int dim = Integer.parseInt(args[0]);
    char [] num = new char[dim];
      for(int i = 49; i < dim; i++){
          for(int j = 0; j < dim; j++){
              num[j] = (char) i ;
          }
          System.out.println(num);
      }
}

Here I changed the code, I added an initial value ascii = 49: But still I am not getting the desired output :(

public static void main(String[] args) {
    int dim = Integer.parseInt(args[0]);
    char [] num = new char[dim];
    int ascii = 49;
      for(int i = 0; i < dim; i++){
          for(int j = 0; j < dim; j++){
              num[j] = (char) (ascii + i) ;
          }
          System.out.println(num);
      }
}

Upvotes: 0

Views: 83

Answers (2)

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147154

int dim = Integer.parseInt(args[0]);

  for(int i = 49; i < dim; i++){

dim will need to be over 49 for the body of this loop to execute, and indeed there is output when you do so.

Edit: With the new code, the inner loop writes the same value over the entire array. The outer for loop does this for incrementing values, printing the array out each time.

Are you trying to do

          num[j] = (char) (ascii + j);

but perhaps without the outer for loop.

Upvotes: 2

Andikan Otung
Andikan Otung

Reputation: 83

Your issue might be here in the first for loop:

for(int i = 49; i < dim; i++){

The for loop will never be entered unless dim is greater than 49 (since you've specified i as 49 with the condition that dim must be greater than i [or i must be less than dim] for the loop to be executed.

If the first for loop is never entered, the print statement is never reached.

Upvotes: 0

Related Questions