Thread: consecutive numbers!

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

consecutive numbers!

I need to find if the number entered by the user are consecutive or not!
Ex:this should return a true!! This should return false!
(1,2,3) (3,5,7)
(3,2,4) (1,2,2)
(-10,-8,-9) (7,7,9)

My program seems to work ok when i enter number in order like 1,2,3 = true , and all the numbers for false seem to be working as well! my problem is when i enter number like 3,2,4 that are not in order but still are consecutive!! can someone please help me!!! i though that another if statement would be the solution but i have tray several different ones and still can't make it work !!!

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) {

char c = str.charAt(0);
for (int cc=1; cc<str.length(); cc++)
if ( (c+1) != str.charAt(cc) )
return false ;
else

c++;
return true;
}//end of consecutive method

}//end of classs
Last edited by Yoana; 02-21-2014 at 10:48 PM.

2. Senior Member
Join Date
Jan 2013
Location
Northern Virginia, United States
Posts
6,226
Rep Power
14

Re: consecutive numbers!

So what you want to know is if a consecutive list can be formed by re-arranging the numbers. Sorting the list might help. Other possibilities would be using either a BitSet, BigInteger (using bits) or a regular Set with some appropriate supporting logic.

Regards,
Jim
Last edited by jim829; 02-22-2014 at 02:30 AM.

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•