Java : Consecutive four equal numbers
阿新 • • 發佈:2021-01-07
Java : Consecutive four equal numbers
Problem Description:
Write the following function that tests whether a two-dimensional list has four consecutive numbers of the same value, either horizontally, vertically, or diagonally.
public static boolean isConsecutiveFour(int[][] values)
Write a test program that prompts the user to enter the number of rows and columns of a two-dimensional list and then the values in the list and displays True if the list contains four consecutive numbers with the same value. Otherwise, display False. Here are some examples of the true cases:
程式碼:
import java.util.Scanner;
public class Ex3_4 {
public static void main(String[] args) {
int[][] m=creatM();
boolean flag=isConsecutiveFour(m);
if(flag) System.out.println("This matrix has four consecutive equal numbers.");
else System.out. println("This matrix don't has four consecutive equal numbers.");
}
public static int[][] creatM(){
Scanner input=new Scanner(System.in);
System.out.print("Enter the number of rows(4- ):");
int row=input.nextInt();
System.out.print("Enter the number of columns(4- ):" );
int column=input.nextInt();
int[][] m=new int[row][column];
System.out.println("Enter this matrix:");
for(int i=0;i<row;i++){
for(int j=0;j<column;j++){
m[i][j]=input.nextInt();
}
}
return m;
}
public static boolean isConsecutiveFour(int[][] m){
return linehas(m)||columnhas(m)||xie_zhu(m)||xie_fu(m);
}
public static boolean linehas(int[][] m){
for(int i=0;i<m.length;i++){
for(int j=0;j<=m[i].length-4;j++){
if((m[i][j]==m[i][j+1])&&
(m[i][j]==m[i][j+2])&&
(m[i][j]==m[i][j+3])){
System.out.println("line.");
return true;
}
}
}
return false;
}
public static boolean columnhas(int[][] m){
for (int j = 0; j < m[0].length; j++) {
for (int i = 0; i <=m.length - 4; i++) {
if ((m[i][j] == m[i+1][j]) && (m[i][j] == m[i+2][j]) &&
(m[i][j] == m[i+3][j])) {
System.out.println("column.");
return true;
}
}
}
return false;
}
public static boolean xie_zhu(int[][] m){
for(int i=0;i<m.length-4;i++){
for(int j=0;j<=m[0].length-4;j++){
if(m[i][j]==m[i+1][j+1]&&
m[i][j]==m[i+2][j+2]&&
m[i][j]==m[i+3][j+3]){
System.out.println("xie_zhu.");
return true;
}
}
}
return false;
}
public static boolean xie_fu(int[][] m) {
for (int i = 3; i < m.length; i++) {
for (int j = 0; j <= m[0].length - 4; j++) {
if (m[i][j] == m[i - 1][j + 1] && m[i][j] == m[i - 2][j + 2] && m[i][j] == m[i - 3][j + 3]) {
System.out.println("xie_fu.");
return true;
}
}
}
return false;
}
}