[英]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.