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

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

  • *7.30(模式识别:四个连续相等的数)编写下面的方法,测试某个数组是否有四个连续相同值的数,那就显示该结论。程序应该首先提示用户键入输入的大小,即列表中值的个数。这里是一个运行示例:
    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
    *7.30(Pattern recognition: four consecutive equal numbers)Write the following method to test whether an array has four consecutive numbers of the same value, which shows the conclusion. The program should first prompt the user to type in the size of the input, the number of values in the list. Here is a running example: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

  • 参考代码:

    package chapter07;
    
    import java.util.Scanner;
    
    public class Code_30 {
        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
    
            System.out.print("Enter the number of values: ");
            int num = input.nextInt();
    
            int[] values = new int[num];
            System.out.print("Enter the values: ");
            for (int i = 0; i < num; i++)
                values[i] = input.nextInt();
    
            if(isConsecutiveFour(values))
                System.out.println("The list has consecutive fours");
            else
                System.out.println("The list has no consecutive fours");
    
            input.close();
        }
    
        public static boolean isConsecutiveFour(int[] values){
            for (int i = 0; i < values.length - 4; i++){
                boolean flag = true;
                for(int j = 1; j < 4; j++)
                    if(values[i+j] != values[i]) {
                        flag = false;
                        break;
                    }
                if(flag)
                    return true;
            }
            return false;
        }
    }
    
    
  • 结果显示:

    Enter the number of values: 9
    Enter the values: 3 4 5 5 6 5 5 4 5
    The list has no consecutive fours
    
    Process finished with exit code 0
    
    
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值