首页 > 解决方案 > 在ArrayList java中查找连续子数组

问题描述

我是java新手,我正在练习。我正在编写一个程序来查找给定整数数组中的所有连续子数组。为简单起见,我从键盘插入输入(每个数字都在新行中),数组末尾的指示是负整数。

我使用这种方法填充数组:

public static void main(String []args){
        // allocate new array       
        ArrayList<Integer> inputArray = new ArrayList<Integer>(); 
        
        int number = 0;
        while(number >= 0) {
            
            // get input from user
            Scanner input = new Scanner(System.in);
            
            number = input.nextInt();
            
            inputArray.add(number);     
        }

        // sort the array
        Collections.sort(inputArray);

       // remove the negative integer (which is stored in the first cell of the array)
       inputArray.remove(0);

        // allocate new array to store the sequence
        ArrayList<Integer> sequence = new ArrayList<Integer>();
        
        // get first cluster
        sequence = FindSequence(0, input);

        for(int it : sequence){
            System.out.println(it);

        }
}

直到这里,一切都按预期工作。

最后,我尝试使用这种方法找到第一个连续整数序列,这不是我的目标,但我从更简单的东西开始,然后我将继续使用这种方法找到所有连续序列:

public static ArrayList<Integer> FindSequence(int index, ArrayList<Integer> input) {
    ArrayList<Integer> sequence = new ArrayList<Integer>();

    while(input.get(index) == input.get(index + 1) || input.get(index) == input.get(index + 1) + 1 ) {
        sequence.add(input.get(index));
        index++;
    }
    
    sequence.add(input.get(index));

    for(int it : sequence) {
            System.out.println(it);
    }
    
    return sequence;
}

这两种方法都在同一个类中声明和实现。

问题是我输入的序列是1 2 3 -1我希望 1 2 3打印的,但我得到的只是输出1。我已经尝试使用 prints 进行一些调试 - 我发现程序没有进入 while 循环,尽管条件已经满足,因为input.get(index) = 1and input.get(index + 1) = 2soinput.get(index) == input.get(index + 1) + 1 是真的。

运算符的||意思是(据我所知)布尔值或,因此必须满足其中一个条件才能使程序进入 while 循环。我真的很困惑,我不知道为什么会这样,也许有人可以解释并建议我如何解决这个问题?

谢谢你。

标签: javaarrays

解决方案


逻辑有点错误,因为下一个元素应该等于前一个元素 + 1 它应该如下所示:

while(input.get(index) == input.get(index + 1) || (input.get(index) + 1) == input.get(index + 1))

推荐阅读