search in an array using for loop

Below is my attempt to search in an array for movies and display them. I have struggling with the java loop as I am not very good with them.

import java.util.Scanner;

public class Main
{
    public static void main(String[] args) {
        while (true) {
            Scanner sc = new Scanner(System.in);  // Create a Scanner object
            
            System.out.print("Search for movie: ");
            String userInput = sc.nextLine();
            
            String[] movies = new String[] { "Spiderman 1", "Spiderman 2", "Spiderman 3"};
            String search = userInput;
            
            boolean searchStatus = false;
            for (int i = 0; i < movies.length; i++){
                if (movies[i].contains(search)) {
                        searchStatus = true;
                    }
                    if (searchStatus == true) {
                        System.out.println("The following movie is a match:");
                    } else {
                        System.out.println("There is no movie called that");
                    }
                    if (movies[i].contains(search)){
                        searchStatus = true;
                        System.out.println(movies[i]);
                    }
            }
        }
    }
}

The output is

Search for movie: 
Spiderman
The following movie is a match:
Spiderman 1
The following movie is a match:
Spiderman 2
The following movie is a match:
Spiderman 3
Search for movie: 
spider
There is no movie called that
There is no movie called that
There is no movie called that

I want my output to look like this instead

Enter title to search for: Spiderman
The following title is a match:
1. Spiderman 1
2. Spiderman 2
3. Spiderman 3

Enter title to search for: spider
There is no movie called that

I need help to have the print statement whether it is a match or not to only print once rather than multiple times. I tried to implement boolean to check the search status but I don’t understand how I can do this, I have been working on this for a few hours now, sorry if this is a noobie question, but I want to know the right way to code rather than repeated code, which currrently looks ugly.

Answer

Have a boolean that checks the existence and for each corresponding match just print the name.

count=0;
boolean searchStatus=false;
for (int i = 0; i < movies.length; i++){
    if (movies[i].contains(search)) {
        if(!searchStatus){
            searchStatus = true;
            System.out.println("The following title is a match:")
        }
        System.out.println((count+1)+". "+movies[i]);//this line adds the required space and the dot as well the count
        count+=1;    
    }
}
if(!searchStatus)
    System.out.println("There is no movie called that");

Leave a Reply

Your email address will not be published. Required fields are marked *