Iterate through string array in Java

后端 未结 10 920
逝去的感伤
逝去的感伤 2020-11-30 01:21

I have String array with some components, this array has 5 components and it vary some times. What I would like to do is to iterate through that array and get the first comp

10条回答
  •  难免孤独
    2020-11-30 02:21

    Those algorithms are both incorrect because of the comparison:

    for( int i = 0; i < elements.length - 1; i++)

    or

    for(int i = 0; i + 1 < elements.length; i++) {

    It's true that the array elements range from 0 to length - 1, but the comparison in that case should be less than or equal to. Those should be:

    for(int i = 0; i < elements.length; i++) {

    or

    for(int i = 0; i <= elements.length - 1; i++) {

    or

    for(int i = 0; i + 1 <= elements.length; i++) {

    The array ["a", "b"] would iterate as:

    i = 0 is < 2: elements[0] yields "a"

    i = 1 is < 2: elements[1] yields "b"

    then exit the loop because 2 is not < 2.

    The incorrect examples both exit the loop prematurely and only execute with the first element in this simple case of two elements.

提交回复
热议问题