Convert a string of numbers into an array

后端 未结 3 1080
盖世英雄少女心
盖世英雄少女心 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:20

    Here is what is happening:

         numbers = keyboard.next();
         System.out.println(numbers);
    
    //This line is creating an array with the length in characters of the String which in this case is 14
         int [] n1 = new int [numbers.length()];
    
    
    //Then When you split the number there is really only 5 elements, yet numbers.length() is 14, therefore when asking for the array on position 6 it causes the exception.
         for(int n = 0; n < numbers.length(); n++) {
            n1[n] = Integer.parseInt(numbers.split(" ")[n]);
    

    Aditionally you should just do this operation numbers.split(" ") once, and then just access it like this:

    String [] stringParts = numbers.split(" "):
    
    stringParts[n]
    

    So basically your for is really something like this:

    for(int n = 0; n < 14; n++)
    {
    
    }
    

    and then numbers.split(" ") returns only 5 elements, since there is a total of 5 numbers, so when you ask for position 6, the exception is thrown as the array is only of size 5.

提交回复
热议问题