第七章第三十题(模式识别:四个连续相等的数)(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