java - 在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) = 1
and input.get(index + 1) = 2
soinput.get(index) == input.get(index + 1) + 1
是真的。
运算符的||
意思是(据我所知)布尔值或,因此必须满足其中一个条件才能使程序进入 while 循环。我真的很困惑,我不知道为什么会这样,也许有人可以解释并建议我如何解决这个问题?
谢谢你。
解决方案
逻辑有点错误,因为下一个元素应该等于前一个元素 + 1 它应该如下所示:
while(input.get(index) == input.get(index + 1) || (input.get(index) + 1) == input.get(index + 1))
推荐阅读
- javascript - ngClass 在 Angular 中与 ngFor 一起使用来切换图标
- android - 使用 Fragment 后更改 Activity 的 Android 错误
- python - 如何在 python/selenium/scraping 中编写这个 if 语句
- javascript - 如何防止 XMLHttpRequest 在连接失败时抛出错误
- python-3.x - 如何合并时间延迟和/或切换代理以避免受到限制?
- python - Python plotly:如何在 Yaxis 上设置 x.xx% 格式
- php - 未捕获的 Autodesk\Forge\Client\ApiException:[504] 连接到 API phpSDK 时出错
- java - 主方法不能引用非静态变量
- javascript - 为什么这个函数调用的执行时间会发生变化?
- r - 如何绘制带有 NA 条目的线图?