【发布时间】:2020-03-08 02:04:31
【问题描述】:
我正在尝试让我的代码提取所有匹配的索引值。我目前不知道如何根据它是否包含输入的相应值来拉取列表的位置值(比如它是否在位置 0、1、2、3 等)。
import java.util.ArrayList;
import java.util.Scanner;
public class Test086 {
public static void main(String[] args) {
Scanner user = new Scanner(System.in);
ArrayList<Integer> array = new ArrayList<>();
int userIn = 0;
System.out.println("Please provide your own array of numbers. Hit enter again to exit the program.");
while (true) {
userIn = Integer.valueOf(user.nextLine());
if (userIn == -1) {
break;
}
else {
array.add(userIn);
}
}
System.out.print("Search for? ");
int index = Integer.valueOf(user.nextLine());
int indSize = array.size() - 1;
for (int i = 0; i < array.size(); i++) {
if (index == array.get(i)) {
System.out.print(index + " is at index ");
}
System.out.println(indSize);
}
}
}
如果我为我的列表输入我的程序:
72
2
8
8
11
-1
Search for? 8
我的期望是将其作为输出:
8 is at index 2
8 is at index 3
什么是我不知道的?有什么方法可以检查位置并将其拉到类似于我拥有的 for 循环?
【问题讨论】:
-
System.out.print(index + " is at index " + i); -
@Kon 哈哈哇!我现在完全明白了。出于某种原因,我没有意识到当我的索引变量和 array.get(i) 在布尔点中相等时,索引位置将在被拉动时保持,直到它再次增加。谢谢!
-
@mightymorphinParkRanger 没问题!这里有一个重要的经验教训是尝试在大脑的工作记忆中保持各种范围变量及其状态。即使是很小的变量也应该在您建立的任何功能的心智模型中占有一席之地。祝你好运!
-
@mightymorphinParkRanger - 你还应该注意stackoverflow.com/questions/60583899/…中提到的一些事情