Iterate through string array in Java

后端 未结 10 791
逝去的感伤
逝去的感伤 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.

    0 讨论(0)
  • 2020-11-30 02:22

    You can do an enhanced for loop (for java 5 and higher) for iteration on array's elements:

    String[] elements = {"a", "a", "a", "a"};   
    for (String s: elements) {           
        //Do your stuff here
        System.out.println(s); 
    }
    
    0 讨论(0)
  • 2020-11-30 02:22
    String[] elements = { "a", "a","a","a" };
    
    for( int i=0; i<elements.length-1; i++)
    {
        String s1 = elements[i];
        String s2 = elements[i+1];
    }
    
    0 讨论(0)
  • 2020-11-30 02:23
    String current = elements[i];
    if (i != elements.length - 1) {
       String next = elements[i+1];
    }
    

    This makes sure you don't get an ArrayIndexOutOfBoundsException for the last element (there is no 'next' there). The other option is to iterate to i < elements.length - 1. It depends on your requirements.

    0 讨论(0)
提交回复
热议问题