(Pattern recognition: consecutive four equal numbers) Write the following method
ID: 3569678 • Letter: #
Question
(Pattern recognition: consecutive four equal numbers) Write the following method that tests whether the array has four consecutive numbers with the same value.
public static boolean isConsecutiveFour(int[] values)
Write a test program that prompts the user to enter a series of integers and displays if the series contain four consecutive numbers with the same value. Your program should first prompt the user to enter the input size-i.e., the number of values in the series. Here are sample runs:
-------------------------------------------------------------
Enter the number of values: 8
Enter the values: 3 4 5 5 5 5 4 5
The list has consecutive fours.
-------------------------------------------------------------
Enter the number of values: 9
Enter the values: 3 4 5 5 6 5 5 4 5
The list has no consecutive fours.
Explanation / Answer
import java.util.Scanner;
public class ConsecutiveFour {
private final int MATCH_COUNT = 4;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number of rows: ");
int rows = input.nextInt();
input.nextLine();
System.out.print("Enter number of columns: ");
int columns = input.nextInt();
input.nextLine();
int[][] matrix = new int[rows][columns];
System.out.println("Enter " + matrix.length + " rows and " + matrix[0].length + " columns: ");
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++){
matrix[row][column] = input.nextInt();
input.nextLine();
int value = matrix[row][column];
}
}
System.out.print("The Four Consecutive Numbers are:" + isConsecutiveFour(matrix));
}
public static boolean isConsecutiveFour(int[][] values) {
boolean cons = false;
int columns = values.length;
int rows = values[0].length;
//tests horizontally
for (int r=0; r < rows; r++) {
for (int c=0; c < columns - 3; c++){
if (values[c][r] == values[c+1][r] &&
values[c][r] == values[c+2][r] &&
values[c][r] == values[c+3][r]) {
cons = true;
}
}
}
return cons;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.