• Post Reply Bookmark Topic Watch Topic
  • New Topic

Checking an array for consecutive numbers  RSS feed

 
Mishra Saurabh
Greenhorn
Posts: 24
Java Netbeans IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Greetings and Thanks in advance to those who help me.
Below is the code to find out if the elements given in the array are consecutive or not
For Example :-
if we get an input array : {1, 2, 3, 4, 5}
print True, otherwise print False
The size of the array is taken input from the user.
Now to my question, is this a good approach or should I choose another, as my assignment marks depend on this program
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Forget about the keyboard input for a bit.
Yes, you can iterate the array testing whether each element is 1 more than its predecessor, but get rid of that empty block in the if. You have written if all right do nothing, otherwise...

The result o your == test is a boolean already, so you can use ordinary boolean algebra:-
consecutive = consecutive && array[i] > array[i - 1] + 1;

Only I didn't give you a correct answer.
 
Carey Brown
Saloon Keeper
Posts: 3323
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You don't need to supply the array size to your method, you can get that with array.length.

I would do your printing in your main() method and have your check method return a boolean.
 
Liutauras Vilda
Sheriff
Posts: 4921
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One more thing. Your checkConsecutive() method supposed to return either true or false, leave the printing part for somebody else - other method in your case.
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another thing: You don't need break;
I know some people prefer break;, but you can write
 
Mishra Saurabh
Greenhorn
Posts: 24
Java Netbeans IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Everyone for the help.
It meant a lot
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!