In: Computer Science
Java. If possible please put explanations for each line of code.
Write a test program that prompts the user to enter a series of integers and displays whether the series contains runLength consecutive same-valued elements. Your program’s main() must prompt the user to enter the input size - i.e., the number of values in the series, the number of consecutive same-valued elements to match, and the sequence of integer values to check. The return value indicates whether at least one run of runLength elements exists in values. Implement the test program as part of the NConsecutive class (the main() method is already in place at the end of the class).
Enter the number of values: 3
How many consecutive, same-valued elements should I look for?
3
Enter 3 numbers: 5 5 5
The list has at least one sequence of 3 consecutive same-valued
elements
Enter the number of values: 3
How many consecutive, same-valued elements should I look for?
4
Enter 3 numbers: 5 5 5
The list has no sequences of 4 consecutive same-valued elements
Here is the code:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
//Scanner Object for input
Scanner sc = new
Scanner(System.in);
//Taking number of values as
input
System.out.print("Enter the number
of values: ");
int n = sc.nextInt();
//Array declaration for storinf
values
int arr[] = new int[n];
//Taking input of How many
consecutive elements to find
System.out.print("How many
consecutive, same-valued elements should I look for?: ");
int c = sc.nextInt();
System.out.print("Enter "+n+"
numbers: ");
//Taking the numbers as input and
storing them to the array
for(int i=0; i<n; i++)
{
arr[i] = sc.nextInt();
}
//Condition if the number of
consecutive elements to be found are less than or equal to total
elements
if(c<=n)
{
//Flag variable
int f=0;
//Checking each consecutive array
possible
for(int i=0; i<=(n-c);
i++)
{
//If all the elements are not same,
turn f=1
f=0;
for(int j=i; j<i+c-1; j++)
{
if(arr[j] != arr[j+1])
f=1;
}
//If f remains zero, that means, we
found a pattern
if(f==0)
break;
}
//Output based on flag
variable
if(f==0)
{
System.out.println("The list has at
least one sequence of "+c+" consecutive same-valued
elements");
}
else
{
System.out.println("The list has no
sequences of "+c+" consecutive same-valued elements");
}
}
else
{
System.out.println("The list has no
sequences of "+c+" consecutive same-valued elements");
}
}
}
Output:
PLEASE UPVOTE IF YOU FOUND IT HELPFUL!