以整数/字符串输入并将其存储在数组中

时间:2016-02-25 14:16:19

标签: java

我如何将Integer用户输入502并以数组形式存储,如arr[0]=5arr[1]=0,arr[2]=2并单独访问。

4 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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]

答案 2 :(得分:1)

您可以使用Integer.toString() functionInteger转换为String,然后使用String.toCharArray() functionString转换为char[]来实现此目的1}}。

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]

答案 3 :(得分:-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;
    }

}