在增强的For循环中使用扫描仪输入在ArrayList中查找对象的索引



我正在尝试接受我的Scanner输入,并使用它来查找对象ArrayList中对象/名称的位置索引。代码由两个类组成,构造函数(setter/getter(和测试程序类数组列表是使用以下代码作为示例创建的;List<Detail> details = new ArrayList<>();

details.add(new Detail("Anthony", 26) );;注意,我使用public void setName(String name)public void setNumber(long number)来识别添加到ArrayList 的对象

数组列表输出看起来像这个

Name: Anthony   Age: 26
Name: Thomas    Age: 30
Name: Shaun Age: 29
Name: James Age: 28

下面的代码是我试图用来查找索引位置的代码。这个代码不会编译,因为我不知道在details.indexOf())的括号里放什么

System.out.print("Type in one of the names listed above to find index of it's location: ");
String name = s.nextLine();
for (Detail d : details){
if (details.contains(s.nextLine()))
System.out.println("The index location of " +(scanner input/name here) " is " + details.indexOf());

我的预期输出是

The index location of Thomas is 1

我知道当一个元素被定义到代码中时,如何获得它的索引,我使用类似int location = details.get(2);的东西,我相信这会返回Name: Shaun Age: 29,但我不知道如何从扫描仪Shaun获取输入,只返回2的位置

我这样做是不是很傻?我做错了什么?

您可以使用以下方法在列表中查找名称的索引。

此处,

  1. 我已经对列表进行了迭代,并使用列表中的名称检查输入,一旦找到,就分配该索引并中断循环。

  2. 如果没有找到用户输入,则用户将被通知消息"0";name not found";。

代码:

带For循环

public class Test {
public static void main(String[] args) {
List<Detail> list = Arrays.asList(new Detail("Anthony",26),
new Detail("Thomas",30),
new Detail("Shaun",29),
new Detail("James",28));
System.out.print("Type in one of the names listed above to find index of it's location: ");
Scanner s = new Scanner(System.in);
String name = s.nextLine();
int index = -1;
for(int i = 0 ;  i < list.size(); i++){
if(name.equals(list.get(i).getName())){
index = i;
break;
}
}
if(index == -1) {
System.out.println("name not found");
} else {
System.out.println("The index location of " + name + " is " + index);
}
}
}

带有增强的For循环

public class Test {
public static void main(String[] args) {
List<Detail> list = Arrays.asList(new Detail("Anthony",26),
new Detail("Thomas",30),
new Detail("Shaun",29),
new Detail("James",28));
System.out.print("Type in one of the names listed above to find index of it's location: ");
Scanner s = new Scanner(System.in);
String name = s.nextLine();
int index = -1;
int counter = 0;
for(Detail d : list){
if(name.equals(d.getName())){
index = counter;
break;
}
counter++;
}
if(index == -1) {
System.out.println("name not found");
} else {
System.out.println("The index location of " + name + " is " + index);
}
}
}

输出::

Input:: Thomas
Output:: The index location of Thomas is 1

Input:: Test
Output:: name not found

最新更新