第八章第十九题(模式识别:四个连续相等的数)(Pattern recognition: four consecutive equal numbers)

第八章第十九题(模式识别:四个连续相等的数)(Pattern recognition: four consecutive equal numbers)

  • **8.19(模式识别:四个连续相等的数)编写下面的方法,测试一个二维数组是否有四个连续相等的数字,这四个数可以是水平方向的、垂直方向的或者对角线方向的。
    public static boolean isConsectiveFour(int[][] values)
    编写一个测试程序,提示用户输入一个二维数组的行数、列数以及数组中的值。如果这个数组有四个连续相等的数字,就显示true;否则,显示false。
    **8.19(Pattern recognition: four consecutive equal numbers)Write the following method to test whether a two-dimensional array has four consecutive equal numbers, which can be horizontal, vertical or diagonal.
    public static boolean isConsectiveFour(int[][] values)
    Write a test program to prompt the user to input the number of rows and columns of a two-dimensional array and the values in the array. If the array has four consecutive equal numbers, it displays true; otherwise, it displays false.

  • 参考代码:

    package chapter08;
    
    import java.util.Scanner;
    
    public class Code_19 {
        public static void main(String[] args) {
            System.out.print("请输入行数和列数: ");
            Scanner input = new Scanner(System.in);
            int row = input.nextInt();
            int column = input.nextInt();
            int[][] numbers=new int[row][column];
    
            for(int i = 0;i < numbers.length;i++){
                for(int j = 0;j < numbers[i].length;j++){
                    numbers[i][j] = input.nextInt();
                }
            }
    
            if (isConsectiveFour(numbers))
                System.out.println("有4个连续相等的数");
            else
                System.out.println("没有4个连续相等的数");
        }
    
        public static boolean isConsectiveFour(int[][] values){
            //判断行
            int countRow;
            for(int i = 0;i < values.length;i++)
            {
                countRow=1;
                for(int j = 1;j < values[i].length;j++)
                {
                    if(values[i][j] == values[i][j - 1])
                        countRow++;
                    else countRow = 1;
    
                    if(countRow == 4)
                        return true;
                }
            }
            //判断列
            int countColumn;
            for (int k = 3; k < values[0].length; k++) {
                countColumn = 1;
                for (int i = 1; i <= k && i < values.length; i++) {
                    int j = k - i;
                    if (values[i][j] == values[i - 1][j + 1])
                        countColumn++;
                    else
                        countColumn = 1;
                    if (countColumn == 4)
                        return true;
                }
            }
            return false;
        }
    }
    
    
  • 结果显示:

    请输入行数和列数: 6 7
    0 1 0 3 1 6 1
    0 1 6 8 6 0 1
    5 6 2 1 8 2 9
    6 5 6 1 1 9 1
    1 3 6 1 4 0 7
    3 3 3 3 4 0 74个连续相等的数
    
    Process finished with exit code 0
    
    

你可能感兴趣的:(#,第八章习题,java,模式识别:四个连续相等的数,小程序,多维数组)