-2

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));
    }
}
  • 4
    I have no idea what you are asking. Did you get an error? If so, what? How did your output differ from the expected? – Mad Physicist Nov 14 '18 at 18:14
  • My output can only display one index – muhariananda Nov 14 '18 at 18:17
  • You scan your array for a match and return the first match and thereby break out of the control flow. you should store all matching indices in a collection. – DmiN Nov 14 '18 at 18:20
  • You should edit the question by clicking on the "edit" button beneath it. A question should contain *all* relevant information. – Mad Physicist Nov 14 '18 at 18:20
  • @m.arianand first welcome to SO. Second, would you please re-read your post and put all the relevant information. Most importantly, you didn't ask any question. What is the question? "How can I improve it" is not a proper question for SO. You have to be specific, otherwise you get down-vote and most importantly no answer. – Rad Nov 14 '18 at 18:33
  • I'm sorry if there's something wrong, I'm new to SO and I'm very grateful for all of your suggestions :) – muhariananda Nov 14 '18 at 18:42

1 Answers1

0

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.

Ivan
  • 8,508
  • 2
  • 19
  • 30