[英]How do I check if a method returns true or false in an IF statement in Java?
[英]Java How do i check for an arraylist object and make it true/false?
该程序做一件事,取决于用户的输入,它将删除一个arraylist对象,并询问您是否要删除另一个对象,但是,如果同一对象试图被删除,我需要程序知道并输出'这样的对象不存在”,例如,“删除“ 3””,然后再次删除“ 3”,程序输出的“ 3”不存在,问题是我不知道如何实现它,我有什么也没有太大的作用。 我的理论是,必须首先使用布尔值检查arraylist对象是否存在,如果存在:删除它,否则:输出“ not there”。 这是我所拥有的:
String[] id1 = { "1", "studentA" };
ArrayList<String> jim = new ArrayList<String>(Arrays.asList(id1));
System.out.println("would you like to remove an id? if so type in "
+ "the id number, otherwise type: no");
Scanner sc = new Scanner(System.in);
String i = sc.next();
int position = -1;
position = jim.indexOf(sc) - 1;
if (position == -1) {
System.out.println("not found in list");
} else {
System.out.println("found and removed");
jim.remove(i);
}
System.out
.println("would you like to remove another id? if so type in "
+ "the id number, otherwise type: no");
Scanner sc2 = new Scanner(System.in);
String j = sc.next();
int position2 = -1;
position2 = jim.indexOf(sc) - 1;
if (position2 == -1) {
System.out.println("not found in list");
} else {
System.out.println("found and removed");
jim.remove(j);
}
我建议使用public boolean remove(Object o)
,如果元素分别与ArrayList
分开,则返回true或false。 您可以将一些布尔变量设置为等于该变量,然后使用if语句输出所需的响应。
boolean contains(Object o)
将检查ArrayList是否包含对象,您可以扫描列表并检查它是否存在。 您还可以使用E get(int index)
进行扫描,并使用循环检查字符串是否彼此相等。
如果您希望程序继续请求用户输入,则需要一个循环,例如while循环 ,该循环仅在用户输入no
时才终止。 除此之外,您可以简单地使用List.remove()
删除元素,并检查返回值(如果该项在列表中并且已被删除,则为true
),以向用户提供正确的反馈:
String[] elements = { "1", "studentA" };
ArrayList<String> list = new ArrayList<String>(Arrays.asList(elements));
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("would you like to remove an id? if so type in "
+ "the id, otherwise type: no");
String input = sc.next();
if ("no".equalsIgnoreCase(input)) {
break; // exit the loop
}
if (list.remove(input)) {
System.out.println("found and removed");
} else {
System.out.println("not found in list");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.