我想检查数组列表中的数字是否是连续的。数组中的数字从 1 开始,下一个元素应该是 2、3 和 4。这意味着下一个元素比前一个元素大 1。
public static void main(String[]args){
ArrayList<Integer> array = new ArrayList<Integer>();
array.add(1); array.add(3);
for (int i = 0; i < array.size(); i++){
if(logic here){
System.out.println(not sequence);
}else{
system.out.pritnln(sequence);
}
}
}
对于这种情况,1 之后应该是 2,但是有 3。我如何实现这种情况的正确逻辑?谢谢你!!!
你可以试试:
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of elements: ");
int input = sc.nextInt();
List<Integer> al = new ArrayList<Integer>();
// Store elements into arraylist
for(int i=0; i<input; i++)
al.add(sc.nextInt());
boolean isSequential = IntStream.range(1, al.size()).allMatch(value -> al.get(value) - al.get(value - 1) == 1);
System.out.println(isSequential ? "Sequential" : "Not Sequential");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)