Reputation: 11
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
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
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