【发布时间】:2018-02-21 11:03:15
【问题描述】:
我正在开发一个程序,该程序向用户询问值,并将它们添加到数组列表中,直到插入值 -1。然后它会询问您要搜索什么值,然后用户插入另一个值。然后程序在数组列表中搜索所有这些值,并打印出所有找到的项目的索引。我的程序目前只打印第一项,它是索引,因为我使用的是 list.indexOf(searcheditem)。我如何让它列出所有找到的项目,而不仅仅是第一个?到目前为止,这是我的代码。
import java.util.ArrayList;
import java.util.Scanner;
public class KysytynLuvunIndeksi {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<>();
while (true) {
int read = Integer.parseInt(reader.nextLine());
if (read == -1) {
break;
}
list.add(read);
}
System.out.print("What are you looking for? ");
int searched = Integer.parseInt(reader.nextLine());
if (list.contains(searched)) {
System.out.println("Value " + searched + " has index of: " + (list.indexOf(searched));
} else {
System.out.println("value " + searched + " is not found");
}
}
}
提前致谢!
【问题讨论】:
-
您好,欢迎来到 StackOverflow!为什么不使用与填写列表相同的方式?但是第二个列表女巫将包含搜索的值?
-
看到这个question
-
在您的问题中,我碰巧注意到,您提到“程序在数组列表中搜索所有这些值”,您是否推断您的程序必须采用超过 1 个值进行搜索?因为您的程序确实只需要 1 个输入。