gpt4 book ai didi

java - 使用 ArrayList 和用户输入在不同索引处查找相同的数字

转载 作者:行者123 更新时间:2023-12-01 16:24:23 26 4
gpt4 key购买 nike

我目前正在尝试解决使用 ArrayList 和用户输入(扫描仪)在不同索引处查找相同数字的编码问题。它不断通过我的测试,但我知道这是错误的,因为它只列出了该数字在列表中的索引之一,而不是列出了该数字也存在的不同索引。我想知道是否有人可以给我任何关于如何解决这个问题的建议或提示。另外,我知道可能有更快的方法来做到这一点,但我目前正在学习 Java 类(class),其中介绍了基础知识,因此请记住这一点。

提前谢谢您!


import java.util.ArrayList;
import java.util.Scanner;

public class IndexOf {

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

ArrayList<Integer> list = new ArrayList<>();
while (true) {
int input = Integer.valueOf(scanner.nextLine());
if (input == -1) {
break;
}

list.add(input);
}

System.out.println("");

int number = Integer.valueOf(scanner.nextLine());

for (int i = 0; i < list.size(); i++) {
int placeholder = list.get(i);
if (number == list.get(i)) {
System.out.println(number + " is at index " + i);
}
if (placeholder == number)
System.out.println(number + " is at index " + i);
} // implement here finding the indices of a number
}
}

最佳答案

你可以尝试这样的事情

search: for(int i=0; i<list.size(); i++) {
for(int j=i+1; j<list.size(); j++) {
if(number == list.get(i) && number == list.get(j)) {
System.out.println("Number is at indices: " + i + ", " + j);
break search;
}
}
}

关于java - 使用 ArrayList 和用户输入在不同索引处查找相同的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62180221/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com