Search code examples
javastringarraylistjava.util.scannerbufferedreader

User Input for Mini Search Engine Program Main Method


I'm writing a mini search engine main method where the search method is :-

public ArrayList<String> top5search(String kw1, String kw2) {}

This is the main :-

public static void main(String[] args) throws IOException 
{

    LittleSearchEngine zoogle = new LittleSearchEngine();
    String kw1 = null,kw2 = null;
    ArrayList<String> kws = new ArrayList<String>();
    //zoogle.makeIndex("docs.txt","noisewords.txt");

    System.out.println("Khajeet search : ");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    Scanner sc = new Scanner(br.readLine());

    while(sc.hasNext())
        kws.add((sc.next()));

    kw1 = kws.get(0);
    kw2 = kws.get(kws.indexOf("or") + 1);

    System.out.println(zoogle.top5search(kw1, kw2));
}

User input (search keywords) will be in the form of String :-

"kw1 or kw2"

Main will extract kw1 & kw2 that's separated by an "or" and top5search will be called. If "or" is not present, top5search will only search for kw1 and kw2 will be null. If "or" is present, then kw1 and kw2 will be used by the method.

May I know how to better streamline the process of determining the above cases? My idea as shown in the main method above is to add all the user input into an arrlist and do the kw1 & kw2 extraction.

Thanks in advance, ZP


Solution

  • That seems to be a good way of handling your input.

    An alternative method could be to just read in the entire line and split it around the "or"s.

    String kws = br.readLine();
    String[] words = kws.split(" or ");
    
    kw1 = words[0];
    if(words.length > 1)
        kw2 = words[1];
    System.out.println(zoogle.top5search(kw1, kw2));
    

    This method allows for multiple consecutive "or" statements as well.