Reputation: 89
I am trying to tell whether that string was found in the list or not. For instance, if I put Max in my list and search for Max, it should say "Max was found" If not, then it should say "Max was not found"
I do not know how to approach to getting the answer from here.
import java.util.ArrayList;
import java.util.Scanner;
public class OnTheList {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<String> list = new ArrayList<>();
while (true) {
String input = scanner.nextLine();
if (input.equals("")) {
break;
}
list.add(input);
}
System.out.print("Search for? ");
System.out.print(scanner.nextLine());
if (list.contains(list)) ----> I think this is the part where I am not getting it
System.out.println(" was found!");
else
System.out.println(" was not found");
}
}
Upvotes: 0
Views: 65
Reputation: 1491
Here you didn't store the user input that you are getting from Search for ,and you are trying to search an element of the list but passing list as the argument for the contains() method ,So first store the user input for a variable the search that input by passing it as the argument to contains() method and make sure to close the scanner variable at the end of the program to avoid memory leaks like below.
import java.util.ArrayList;
import java.util.Scanner;
public class OnTheList {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<String> list = new ArrayList<>();
while (true) {
String input = scanner.nextLine();
if (input.equals("")) {
break;
}
list.add(input);
}
System.out.print("Search for? ");
String toSearch = scanner.nextLine();
if (list.contains(toSearch))
System.out.println(" was found!");
else
System.out.println(" was not found");
scanner.close();
}
}
Upvotes: 0
Reputation: 54148
You may store the word to search, here you ask for it with scanner.nextLine()
and print it but didn't save it. Then use the variable you saved the word in, to check into the List
System.out.print("Search for? ");
String toSearch = scanner.nextLine();
if (list.contains(toSearch))
System.out.println(toSearch + " was found!");
else
System.out.println(toSearch + " was not found");
Upvotes: 1