0

I have written code so from console window I can search on Google directly, but if I give space in keywords it gives an error. I know what the problem is because if we search with giving space in Google in its link +-sign gets added, so I am not able to figure out what kind of logic I can make.

For example, if I search "IronMan", it will work, but if I search it as "Iron Man", then it only takes Iron because in this part String searchURL = GOOGLE_SEARCH_URL + "?q=" + searchTerm;, searchTerm is the word where Ironman gets inserted, but if we put Iron Man, then searchTerm must fill it as Iron+Man so can somebody help me making the logic please .

Below is the code:

package research;

import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.InputMismatchException;
import java.util.Scanner;

public class google {

    public static final String GOOGLE_SEARCH_URL = "https://www.google.com/search";

    public static void main(String[] args)throws InputMismatchException {
        int ch=0;
        
        do{
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please enter the search term.");
        String searchTerm =scanner.nextLine();
        
        String searchURL = GOOGLE_SEARCH_URL + "?q=" + searchTerm;
        
        if (Desktop.isDesktopSupported())
            try {
            Desktop.getDesktop().browse(new URI(searchURL));
            } catch (IOException e1) {
            e1.printStackTrace();
            } catch (URISyntaxException e1) {
            e1.printStackTrace();
            }

        
        System.out.println("Want to search more \n 1.y or \n 2.n");
        ch=scanner.nextInt();
        }while(ch==1);
    }

}
Mark Rotteveel
  • 90,369
  • 161
  • 124
  • 175

0 Answers0