Search code examples
javasequential

Sequential search in Java


Here I have learned to make programs in java about sequential searches. But in my program, I realized there was something that needed to be added or improved, but I was confused about how. Can anyone give me a suggestion, thank you.

example.

enter sentence : BOOK
enter letter : O
Letter O is in the index : 1 , 2

My program code.

public class sequentialSearch {

    public static int sequential(String read, char target) {
        char[] arr = read.toCharArray();
        for(int i = 0 ; i < arr.length ; i++){
            if(arr[i] == target) {
                return  i;
            }
        }
        return 0;
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("enter sentence: : ");
        String read = input.next();
        System.out.print("enter letter : ");
        char target = input.next(".").charAt(0);

        System.out.print("Letter "+target+" is in the index – ");
        System.out.println(sequetial(ars,target));
    }
}

Solution

  • You use return i; when find first match. And return exits your loop and whole sequential() function. You either need to return array or list of indexes or replace return i with simply printing that index.