97.6k views
1 vote
Write in java:

A number consists of consecutive numbers if each digit differs by exactly 1. For example, each of the following integers is a consecutive number: 1234, 5432, 6789 and 9876. Write a program that asks the user to enter an integer and determines if it consists of consecutive numbers or not. The number can have any number of digits.

Sample run 1:

Enter an integer: 1234345676
consecutive

Sample run 2:

Enter an integer: 45896725
not consecutive

1 Answer

6 votes

Here's a Java program that checks whether a given number consists of consecutive digits or not:

```java

import java.util.Scanner;

public class ConsecutiveNumbers {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter an integer: ");

long number = scanner.nextLong();

if (isConsecutiveNumber(number)) {

System.out.println("consecutive");

} else {

System.out.println("not consecutive");

}

scanner.close();

}

public static boolean isConsecutiveNumber(long number) {

String numStr = String.valueOf(number);

for (int i = 0; i < numStr.length() - 1; i++) {

int currentDigit = Character.getNumericValue(numStr.charAt(i));

int nextDigit = Character.getNumericValue(numStr.charAt(i + 1));

if (Math.abs(currentDigit - nextDigit) != 1) {

return false;

}

}

return true;

}

}

```

In this program, the `isConsecutiveNumber` method takes a long number as input and checks if it consists of consecutive digits. It converts the number to a string and iterates through each digit. It compares the absolute difference between each digit and its adjacent digit. If the difference is not equal to 1 for any pair of digits, the method returns `false`. If all pairs of digits have a difference of 1, the method returns `true`.

The `main` method prompts the user to enter an integer, calls the `isConsecutiveNumber` method to check if it consists of consecutive digits, and prints the appropriate message based on the result.

User Matt Le Fleur
by
7.9k points

Related questions

asked Feb 3, 2022 99.4k views
IDhaval asked Feb 3, 2022
by IDhaval
8.0k points
2 answers
4 votes
99.4k views
asked Oct 15, 2017 227k views
Teliatko asked Oct 15, 2017
by Teliatko
8.3k points
2 answers
0 votes
227k views