Print length of longest sequence of consecutive numbers Problem H (Longest Natural Successors):


  Two consecutive integers are natural successors if the second is the
  successor of the first in the sequence of natural numbers (1 and 2 are
  natural successors). Write a program that reads a number N followed by
  N integers, and then prints the length of the longest sequence of
  consecutive natural successors.
  
  Example:

Input  7 2 3 5 6 7 9 10
Output 3



This is my code so far:

  import java.util.Scanner;


    public class Conse {

  public static void main(String[] args) {
    // TODO Auto-generated method stub
     Scanner scan = new Scanner(System.in); 
     int x=scan.nextInt();
     int[] array= new int[x];
     for(int i=0;i&lt;array.length;i++)
         array[i]=scan.nextInt();
     System.out.println(array(array));
      }
public static int array(int[] array){
    int count=0,temp=0;
    for(int i=0;i&lt;array.length;i++){
        count=0;
        for(int j=i,k=i+1;j&lt;array.length-1;j++,k++)
            if(array[j]-array[k]==1)
                count++;
            else{if(temp&lt;count)
                temp=count;
            break;}
        }
    return temp+1;
 } 

  }
Using static for the consecutive() function is appropriate.  However, the omission of braces, the inconsistent indentation, and lack of spaces between operators is just as bad as before.

Your function crashes on arrays of length 0 or 1.

The variable names f and counter could be improved.  I think that a different looping structure would be clearer as well.

public static int consecutive(int[] array) {
    if (array.length &lt;= 1) {
        return array.length;
    }

    int maxRun = 0;
    for (int i = 1; i &lt; array.length; i++) {
        int thisRun = 1;
        while (i &lt; array.length &amp;&amp; array[i - 1] + 1 == array[i]) {
            thisRun++;
            i++;
        }
        if (maxRun &lt; thisRun) {
            maxRun = thisRun;
        }
    }
    return maxRun;
}