在ArrayList Java中查找连续子数组

时间:2020-09-12 09:41:22

标签: java arrays

我是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。 我尝试使用打印调试一下-我发现程序没有进入while循环,尽管条件已经满足,因为input.get(index) = 1input.get(index + 1) = 2因此input.get(index) == input.get(index + 1) + 1是真实的

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

谢谢。

3 个答案:

答案 0 :(得分:1)

逻辑有些错误,因为下一个元素应该等于前任+ 1 它应该看起来像这样:

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

答案 1 :(得分:1)

input.get(index) == input.get(index + 1) + 1行中,您要检查下一个索引是否比当前索引大1。

要进行相同的检查,请在当前元素加1后等于下一个元素。相同的布尔语句可以是

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

答案 2 :(得分:1)

这是您正在使用的条件检查,它违反了找到连续序列的整个目的。下面的代码可以正常工作。

import java.io.*;
import java.util.*;

class GFG {
 public static void main (String[] args) {
    ArrayList<Integer> list = new ArrayList<>();
    list.add(1);
    list.add(2);
    list.add(3);
    list.add(-1);
    FindSequence(0,list);
 }

 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) + 1 == input.get(index + 1)) {
    sequence.add(input.get(index));
    index++;
 }

  sequence.add(input.get(index));

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