Ssarah
Ssarah

Reputation: 11

Extract domain name from user input url

I am having a problem extracting the domain name from any url a user can input. We have to test our program with http://www.google.com, http://amazon.com and http://mix.wvu.edu.

import java.util.Scanner;

    public class lab3 { 

        public static void main( java.lang.String[] args) { 
            System.out.println ("Please enter the URL");
            Scanner in = new Scanner(System.in);
            String Url = in.nextLine(); 
            System.out.println();
        }
    }

This sad bit of java is what I have so far, I'm just not sure what step is next after i have the user enter the Url! any help would be amazing!

Upvotes: 1

Views: 1563

Answers (3)

Nealvs
Nealvs

Reputation: 306

Using the java.net.URL class, you can initialize an instance of it and pass the entire input string into the constructor. Then use the url.getHost() method to have the class extract the domain name for you.

import java.net.URL;
import java.util.Scanner;

public class lab3 {

    public static void main( java.lang.String[] args) { 
        try {
            System.out.println ("Please enter the URL");
            Scanner in = new Scanner(System.in);
            String input = in.nextLine(); 
            URL url = new URL(input);
            System.out.println(url.getHost());
        } catch(Exception ex) {
            ex.printStackTrace();
        }
    }
}

Upvotes: 2

Stephen C
Stephen C

Reputation: 718886

Construct an instance of the java.net.URL class from the string and use the relevant getter to get the host component. Details are in the javadoc linked above. (java.net.URI is another option, but if the input should be a URL not a URI then the URL class should be less hassle in this case.)

Upvotes: 0

hd1
hd1

Reputation: 34657

You may consider looking at the URI class, specifically, the getHost method. Good luck!

Upvotes: 1

Related Questions