字符串数组为int

时间:2017-12-04 16:00:38

标签: java

String[] card = { "2", "2", "2", "2",
    "3", "3", "3", "3",
    "4", "4", "4", "4",
    "5", "5", "5", "5",
    "6", "6", "6", "6",
    "7", "7", "7", "7",
    "8", "8", "8", "8",
    "9", "9", "9", "9",
    "10", "10", "10", "10",
    "11", "11", "11", "11",
    "12", "12", "12", "12",
    "13", "13", "13", "13",
    "14", "14", "14", "14",};

我试图将此数组转换为int数组,以便我可以在二十一点程序中使用它。任何想法?

1 个答案:

答案 0 :(得分:1)

这很容易。只需创建一个类型为int[]的新数组,迭代所有String个元素,将它们转换为int(使用Integer.parseInt(String)),然后将该元素添加到结果数组中。 / p>

String[] cardsText = ...

// Create new int array
int[] cards = new int[cardsText.length];

// Iterate all elements
for (int i = 0; i < cardsText.length; i++) {
    // Get String element
    String cardText = cardsText[i];
    // Parse to int
    int card = Integer.parseInt(cardText);
    // Add int to array
    cards[i] = card;
}

或者使用 Stream API (Java 8)

String[] cardsText = ...

int[] cards = Arrays.stream(cardsText)  // Stream<String>
    .mapToInt(Integer::parseInt)        // IntStream
    .toArray();                         // int[]

如果您的特定应用程序有可能,您也可以直接使用int[]数组而不首先创建String[]

int[] card = { 2, 2, 2, 2,
    3, 3, 3, 3,
    4, 4, 4, 4,
    5, 5, 5, 5,
    6, 6, 6, 6,
    7, 7, 7, 7,
    8, 8, 8, 8,
    9, 9, 9, 9,
    10, 10, 10, 10,
    11, 11, 11, 11,
    12, 12, 12, 12,
    13, 13, 13, 13,
    14, 14, 14, 14 };