java integer array convert to ascii and put into char array

here is question Write a method that generates an int array as a parameter, converts the generated integers into characters and print the new char array. Array values should be in the range [0 -255].

public static void main(String[] args) {
    char[] array1 = new char [100];
    int d;
    int[] array = getArray();
    convert(array,array1);
    for (int i = 0; i < array.length; i++) {
        System.out.print(array[i] + " ");
    }
    System.out.println();
    for (int i = 0; i < 100; i++) {
        System.out.print(array1[i] + " ");
    }
}

public static int convert(int[] array, char[] array1) {
    for (int a=0;a<100;a++) {
        array [a] = toChars(array1[a]);
    }
}

public static int[] getArray() {
    int[] array = new int[100];
    for (int i = 0; i < array.length; i++) {
        array[i] = (int)(Math.random() * 255);
    }
    System.out.println();
    return array;
}

I have encountered few problem with that. I could not convert integer to ASCII code. What I can use instead of:

for (int a=0;a<100;a++) {
    array [a] = toChars(array1[a]);
}

Upvotes: 0

Views: 6787

Answers (2)

user1178540
user1178540

Reputation:

You could do something like this:

public static void convert(int[] array, char[] array1) {
    int length = array.length;
    for (int i = 0; i < length; i++) {
        // this converts a integer into a character
        array1[i] = (char) array[i];
    }
}

Upvotes: 1

SMA
SMA

Reputation: 37063

Your convert method should be:

public static void convert(int[] array, char[] array1) {
    for (int a = 0; a < 100; a++) {
        array1[a] = (char) array[a];
    }
}

Just type cast int to char.

Upvotes: 0

Related Questions