Splitting String and put it on int array

后端 未结 8 1403
眼角桃花
眼角桃花 2020-11-28 14:03

I have to input a string with numbers ex: 1,2,3,4,5. That\'s a sample of the input, then I have to put that in an array of INT so I can sort it but is not working the way it

8条回答
  •  日久生厌
    2020-11-28 14:40

    For input 1,2,3,4,5 the input is of length 9. 9/2 = 4 in integer math, so you're only storing the first four variables, not all 5.

    Even if you fixed that, it would break horribly if you passed in an input of 10,11,12,13

    It would work (by chance) if you used 1,2,3,4,50 for an input, strangely enough :-)

    You would be much better off doing something like this

    String[] strArray = input.split(",");
    int[] intArray = new int[strArray.length];
    for(int i = 0; i < strArray.length; i++) {
        intArray[i] = Integer.parseInt(strArray[i]);
    }
    

    For future reference, when you get an error, I highly recommend posting it with the code. You might not have someone with a jdk readily available to compile the code to debug it! :)

提交回复
热议问题