Convert a string of numbers into an array

后端 未结 3 1102
盖世英雄少女心
盖世英雄少女心 2021-01-26 10:44

i\'m having problems creating a program that converts a string of numbers into an array.

i know there is a similar question on here, but all i have to work with is a se

3条回答
  •  长发绾君心
    2021-01-26 11:16

    You should split the string once and store the array somewhere.

    Here you are iterating up to the number of characters in the string, not the number of space-separated numbers.

    int [] n1 = new int [numbers.length()];
    for(int n = 0; n < numbers.length(); n++) {
       n1[n] = Integer.parseInt(numbers.split(" ")[n]);
    }
    

    Change to:

    String[] parts = numbers.split(" ");
    int[] n1 = new int[parts.length];
    for(int n = 0; n < parts.length; n++) {
       n1[n] = Integer.parseInt(parts[n]);
    }
    

    See it working online: ideone

提交回复
热议问题