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

前端 未结 3 1831
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-26 21:13

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.*;
         


        
相关标签:
3条回答
  • 2021-01-26 21:47

    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
    
    0 讨论(0)
  • 2021-01-26 22:00

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

    digit[count])
    

    just use

    digit
    
    0 讨论(0)
  • 2021-01-26 22:03

    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++;
    
    }
    
    0 讨论(0)
提交回复
热议问题