# consecutive numbers!

• 02-23-2014, 11:56 PM
Yoana
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!
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 }```
• 02-24-2014, 12:08 AM
jim829
Re: consecutive numbers!
First, why did you repost this again and not just continue with your first thread --> http://www.java-forums.org/new-java/85606-consecutive-numbers.html?

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
• 02-24-2014, 01:03 AM
Norm
Re: consecutive numbers!
Quote:

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?
• 02-24-2014, 08:09 PM
Yoana
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)
• 02-24-2014, 08:10 PM
Yoana
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)