Computer Science, asked by ishitasarkar400, 1 year ago

input a three digit number and print if it is a consecutive number

a consecutive number is the number that follow each other in order and have a difference of 1
example-123,321,456,654etc
the program is to be done in java and input using scanner class
please answer quickly and no spams please

Answers

Answered by rakeshchennupati143
0

Program:

import java.util.*;

public class Main{

     public static void main(String[] args) {

           System.out.println("Enter a 3 digit number:");

           Scanner sc = new Scanner(System.in);

           int number = sc.nextInt();

           if( number > 99 && number < 1000 ){

                 String ch = Integer.toString(number);

                 int p1 = ch . charAt(0), p2 = ch . charAt(1), p3 = ch . charAt(2);

                 if((p1 == (p2+1)) || ((p1+1) == p2)){

                       if((p2 == (p3+1)) || ((p2+1) == p3)){

                             System.out.println("The number "+number+" is consecutive number");

                       }else{

                             System.out.println("The number "+number+" is not a consecutive number");

                       }

                 }else{

                       System.out.println("The number "+number+" is not a consecutive number");

                 }

           }else{

                 System.out.println("You should give a 3 digit number");

           }

     }

}

Output-1:

Enter a 3 digit number:123

The number 123 is consecutive number

Output-2:

Enter a 3 digit number:125

The number 125 is not a consecutive number

Output-3:

Enter a 3 digit number:1234

You should give a 3 digit number

Explanation:

  • first i took number into number variable of int type
  • then i converted it into string using Integer.toString() and then converted each character of the string into its ascii value using a trick which converts any character to ascii when that character is assigned to int type
  • and then i check those ascii values one by one in if condition if all the conditions are true then it says the given value is a consecutive number
  • or else it will say it is not a consecutive number

----Hope you liked my program, if you liked it mark brainliest, it world really help me  :)


ishitasarkar400: can u do this without using string?
Similar questions