1

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!

3 Answers 3

2

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();
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.