Write a program in Java that determines if a string is a series of up to 10 cons
ID: 3764342 • Letter: W
Question
Write a program in Java that determines if a string is a series of up to 10 consecutive sequence numbers or the number sequence contains the same number. The program must call for user input in which the numbers are separated by the dash character, e.g., “16-17-18-19”, “102-101-100-99-98-97”, “56-57-57”. The program should display “Correct consecutive sequence”, “Incorrect consecutive sequence”, “Pair of numbers found”, “Pair of numbers not found” and/or “Invalid Input”. The program must iteratively ask for user input until a terminating character is entered. The program must have at least 2 functions excluding the main() function.
Explanation / Answer
import java.util.Scanner;
/**
*
*/
/**
* @author srinu
*
*/
public class ConsecutiveSequence {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// “16-17-18-19”, “102-101-100-99-98-97”, “56-57-57”
while (true) {
String input = readString();
if (input.contains("n")) {
break;
} else {
System.out.println(isSequence(input));
}
}
}
/**
* to caliculate correct/incorrect or paired sequence
*
* @param input
* @return
*/
public static String isSequence(String input) {
try {
String inputArr[] = input.split("-");
// System.out.println(inputArr.length);
if (inputArr.length == 1) {
return "Invalid Input";
}
for (int i = 1; i < inputArr.length; i++) {
int curr = Integer.parseInt(inputArr[i]);
int prev = Integer.parseInt(inputArr[i - 1]);
int diff = curr - prev;
if (Math.abs(diff) == 1) {
} else if (Math.abs(diff) == 0) {
return "Pair of numbers found";
} else {
return "Incorrect consecutive sequence";
}
}
} catch (Exception e) {
// TODO: handle exception
return "Invalid Input";
}
return "Correct consecutive sequence";
}
/**
* to read a string
*
* @return input string
*/
public static String readString() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the Number Series(n for exit) :");
String input = scanner.nextLine();
return input;
}
}
OUTPUT:
Enter the Number Series(n for exit) :45+55
Invalid Input
Enter the Number Series(n for exit) :3-2-1
Correct consecutive sequence
Enter the Number Series(n for exit) :5-6-7-8
Correct consecutive sequence
Enter the Number Series(n for exit) :4-5-6-6
Pair of numbers found
Enter the Number Series(n for exit) :7-6-4-2
Incorrect consecutive sequence
Enter the Number Series(n for exit) :n
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.