Description: Create a Java program that prompts user for a sequence of integers
ID: 3550409 • Letter: D
Question
Description: Create a Java program that prompts user for a sequence of integers of length one or more, and prints the length of the longest sorted subsequence and its starting position.
For example, the user is asked for input and provides the following sequence: 4, 3, 2, 7, 9, 12, 11, 12, 13, 14, 15, 16, 15, 27.
The program will display the following:
Max sorted subsequence length = 6 starts at 7
If there is more than one subsequence of equal maximum length, the subsequence that appears first (the
one with the smallest index) is to be used for the output.
***Program must be implemented as a Java program that uses:
___________________________________________________________________________________________________
Sample interactions:
Enter one or more integers follwed by Ctrl+Z (Windows) or Ctrl+D (Mac)
8
Max sorted subsequence length = 1 starts at 1
Enter one or more integers follwed by Ctrl+Z (Windows) or Ctrl+D (Mac)
9 26
Max sorted subseqence length = 2 starts at 1
Enter one or more integers follwed by Ctrl+Z (Windows) or Ctrl+D (Mac)
4 12 14 16 11 12 13 14 15 16 16 18 19 8 10
Max sorted subseqence length = 9 starts at 5
Enter one or more integers follwed by Ctrl+Z (Windows) or Ctrl+D (Mac)
20 19 21 6 10 11 4 5 6 3 4
Max sorted subsequence length = 3 starts at 4
____________________________________________________________________________________________________
Keep in mind, the program should be designed with a beginner's level of programming. Nothing too advanced or something you would see from an intermidiate programmer.
I will be sure to give the points to whomever provides the most simple, basic and accurate program. Thanks, Everyone!
Explanation / Answer
//Enter the values and lf you want to stop entering values enter as -1.....
//As Eclipse does not allow ctrl+z....making the check with -1
package RoyalFarmer;
import java.util.Scanner;
public class LongestSubsequence {
/**
* @param args
*/
public static void main(final String[] s) {
int counter = 0;
int highestCount = 0;
int previousNum = 0;
int position = 0;
int latestStartingPosition = 0;
int startingPosition = 0;
int inputValue;
try (final Scanner sc = new Scanner(System.in)) {
while ((inputValue = sc.nextInt()) != -1) {
if (previousNum <= inputValue) {
counter++;
if (counter > highestCount) {
highestCount = counter;
startingPosition = latestStartingPosition;
}
} else {
latestStartingPosition = position;
counter = 1;
}
previousNum = inputValue;
position++;
}
}
System.out.println("starting pos: " + startingPosition);
System.out.println("Number of repeating positions: " + highestCount);
}
}