簡體   English   中英

以整數/ string取輸入並將其存儲在數組中

[英]Taking input in integer /string and store it in array

我將如何使用Integer用戶輸入(例如502並將其存儲為數組形式(如arr[0]=5arr[1]=0,arr[2]=2並分別進行訪問。

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

您可以嘗試以下方法:

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]

您可以通過使用Integer.toString()函數Integer轉換為String ,然后使用String.toCharArray()函數來將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]

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;
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM