2016-02-25 54 views

回答

1

您可以通過使用Integer.toString() function改造做到這一點你IntegerString和然後使用String.toCharArray() function,這將改變您的String轉換爲char[]

public class Program { 

    public static void main(String[] args) { 
     // Declare your scanner 
     Scanner sc = new Scanner(System.in); 

     // Waits the user to input a value in the console 
     Integer integer = sc.nextInt(); 

     // Close your scanner 
     sc.close(); 

     // Put your string into a char array 
     char[] array = integer.toString().toCharArray(); 

     // Print the result 
     System.out.println(Arrays.toString(array)); 
    } 
} 

輸入:502

輸出:[5, 0, 2]

1
char[] charArray = String.valueOf(inputInt).toCharArray(); 
1

你可以試試這個:

char[] chars = String.valueOf(520).toCharArray(); // it is the cahr array 
// if you want to convert it integer array you can it as below 
int[] array = new int[chars.length]; 
for (int i = 0; i < array.length; i++) { 
    array[i] = chars[i]; 
} 
System.out.println("array = " + Arrays.toString(chars)); 

而且它的輸出:

array = [5, 2, 0] 
-1
public class MyClass { 

    public static int[] toArray(String input) { 
     // 1) check if the input is a numeric input 
     try { 
      Integer.parseInt(input); 
     } catch (NumberFormatException e) { 
      throw new IllegalArgumentException("Input \"" + input + "\" is not an integer", e); 
     } 

     // 2) get the separate digit characters of the input 
     char[] characters = input.toCharArray(); 
     // 3) initialize the array where we put the result 
     int[] result = new int[characters.length]; 
     // 4) for every digit character 
     for (int i = 0; i < characters.length; i++) { 
      // 4.1) convert it to the represented digit as int 
      result[i] = characters[i] - '0'; 
     } 

     return result; 
    } 

} 
+0

Downvoters請留下不好的事評論,所以我可以改進和/或學習新的東西 –