1. Member
Join Date
Oct 2013
Posts
10
Rep Power
0

## consecutive numbers!

im trying to do a program to find if numbers are consecutive or not! if they are consecutive i need a true as a return and a false when they are not... i did this program and im sure i did something wrong because i keep only true returns .. can anyone please see my code and let me know what i did wrong!
Example: (3,5,7) (1,2,2) (7,7,9) should return a false!
Java Code:
import java.util.*;
public class Consecutive{
public static void main (String [] args){
Scanner console= new Scanner(System.in);
System.out.println("Enter three numbers");
String numbers = console.nextLine();
System.out.println( "The numbers (" + numbers + ") is '" + consecutive( numbers ) + "'" );
}//end of main

private static boolean consecutive(String str) {
String[] numbers = str.split(",");
Arrays.sort(numbers);
for (int index = 0; index < numbers.length-1; index++){
if (Integer.parseInt(numbers[index]) > Integer.parseInt(numbers[index+1])){
return false;
}
}
return true;
}//end of consecutive method
}

2. Senior Member
Join Date
Jan 2013
Location
Northern Virginia, United States
Posts
5,743
Rep Power
10

## Re: consecutive numbers!

First, why did you repost this again and not just continue with your first thread --> consecutive numbers!?

In any event, your logic is working fine for the sets you provided. You are checking if the first is greater than the second and if the second is greater than the third. Perhaps you should reverse your notion of what is false and true.

BTW, what is your definition of consecutive? Are either of these sets consecutive?

{1,3,4}
{4,3,1}

Because no matter where you return true or false in the code above, one of these will return true and one will return false.

Regards,
Jim

3. ## Re: consecutive numbers!

let me know what i did wrong
Can you describe the algorithm the code uses to solve the problem?
Are there other algorithms that work better?

How many passes can be made over the array?

4. Member
Join Date
Oct 2013
Posts
10
Rep Power
0

## Re: consecutive numbers!

someone mentioned that it may be easier using an array so that is why i stop working in the other program and started a new one. !
(1,3,4) as well as (4,3,1)

5. Member
Join Date
Oct 2013
Posts
10
Rep Power
0

## Re: consecutive numbers!

someone mentioned that it may be easier using an array so that is why i stop working in the other program and started a new one. !
(1,3,4) as well as (4,3,1)