user1768884
user1768884

Reputation: 1047

Trying to convert a char array to integer array in Java with this code

I'm trying to convert an array of characters into integers, so I can get the ascii code, but the code I have doesn't seem to be working.

import javax.swing.*;
import java.text.*;
import java.util.*;
import java.lang.*;

public class Encrypt {


public static void main(String[] args) {

String phrase = JOptionPane.showInputDialog(null, "Enter phrase to be messed with ");
char[] charArray = phrase.toCharArray();

for (int count = 0; count < charArray.length; count++) {
int digit = ((int)charArray[count]);

System.out.println(digit[count]);

}




}

Upvotes: 1

Views: 8544

Answers (3)

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

Try it this way...

char[] charArray = phrase.toCharArray();

int[] intArray = new int[charArray.length];

int i=0;

for (char c : charArray){

      intArray[i] = c;
      i++;

}

Upvotes: 0

kosa
kosa

Reputation: 66637

You don't need to explicitly cast it. You may simply assign it to int. Refer 5.1.2. Widening Primitive Conversion

Example:

 char[] charArray = "test".toCharArray();

        for (int count = 0; count < charArray.length; count++) {
            int digit = charArray[count];

            System.out.println(digit);

        }

output:

116
101
115
116

Upvotes: 2

Jigar Joshi
Jigar Joshi

Reputation: 240890

digit is an int type primitive variable can't be treated as an array

digit[count])

just use

digit

Upvotes: 2

Related Questions