英文:
Finding all Index's of specific Element in ArrayList (Int)
问题
我最近开始学习Java编程(也许对我来说已经变得太难了),我每天都在做一些练习来进行实践。我需要完成其中一个挑战,那就是搜索一个元素(int),如果它在数组中,就应该显示索引(如果在数组中找到元素重复,则应显示所有索引)。
以下是我目前的代码!
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("");
// 在这里实现查找数字的索引
System.out.println("搜索元素?");
int arraySize = list.size();
int numToSearch = Integer.valueOf(scanner.nextLine());
for (int i = 0; i < arraySize - 1; i++) {
int pos = list.indexOf(numToSearch);
if (list.indexOf(i) == pos) {
System.out.print(numToSearch + " 在索引位置:" + pos);
}
}
}
}
到目前为止,我已经成功让它打印出我搜索的元素的索引,但它只对它找到的第一个正确索引执行此操作。
抱歉代码有些混乱,我还没有学习到如何编写整洁的代码!
英文:
I recently got into Java Programming (Maybe it's already getting too hard for me), and I'm doing some exercises daily to practise. One of the challenges I need to do, is to search an Element (int), and if it's in the Array, the Index should be displayed (All index's should be displayed if Element duplicates found in Array).
Here's the code I have so far!
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("");
// implement here finding the indices of a number
System.out.println("Search for?");
int arraySize = list.size();
int numToSearch = Integer.valueOf(scanner.nextLine());
for(int i = 0; i <arraySize-1; i++){
int pos = list.indexOf(numToSearch);
if(list.indexOf(i)==pos){
System.out.print(numToSearch+" is at Index: "+pos);
}
}
}
}
So far I've managed to get it to print the Index of the Element I search for, but it only does it for the first correct Index it finds.
Sorry for the clunky code, haven't yet learnt much in terms of neat code!
答案1
得分: 0
在最后一个循环中,您正在检查list
中numToSearch
的索引与list
中0...arraySize-2
的索引之间的相等性。除非我对问题的理解有误,正确的方法应该是检查每个数组成员与numToSearch
的相等性。然后打印出具有当前索引的字符串。
可以表示如下:
for (int i = 0; i < arraySize; i++) {
if (list.get(i) == numToSearch) {
System.out.println(numToSearch + " 在索引处:" + i);
}
}
英文:
In the last loop, you were checking the equality between the index of numToSearch
in list
and the index of 0...arraySize-2
in list
. Unless I am understanding the question incorrectly, the correct approach should be checking the equality of each array member and numToSearch
. Then print out the string with the current index you are at.
This could be represented like this:
for (int i = 0; i < arraySize; i++) {
if (list.get(i) == numToSearch) {
System.out.println(numToSearch + " is at Index: " + i);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论