user3416645
user3416645

Reputation: 23

URL Input and Format

I am trying to get user input and print out the contents from the URL received. I have just about everything I need but I need help getting the user input to only have http://. From there I would to move it into my string in order to show it's contents. I also keep getting the java.net.MalformedURLException: no protocol error. How can I fix this and implement this code?

import java.util.*;
import java.io.PrintWriter;
import java.util.Scanner;
import java.net.URL;
import java.io.IOException;
import java.net.URLConnection;

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

       System.out.println ("Enter a URL");
            Scanner myInput = new Scanner(System.in);
            String input = myInput.nextLine(); 
            URL url = new URL(input);
            //Here I want to add user input and get a URL that only contains http://

    String address = " ";
    URL pageLocation = new URL(address);
    Scanner in = new Scanner(pageLocation.openStream());
    while (in.hasNext())
    {
      String line = in.next();
      if (line.contains("href=\"http://"))
      {int from = line.indexOf("\"");
        int to = line.lastIndexOf("\"");
    System.out.println(line.substring(from + 1,to));
  }
}
  }
}
  }

Upvotes: 1

Views: 2299

Answers (2)

merlin2011
merlin2011

Reputation: 75565

I am guessing you want to keep asking the user until they give you an appropriate URL.

Change this line

String input = myInput.nextLine(); 

To

String input = null;
while (true) {
  input = myInput.nextLine(); 
  if (input.startsWith("http://")) break;
  System.out.println("Your URL must start with http://. Please try again!");
}

This basically continues to prompt the user until they enter a URL with the prefix http://. Of course you should probably change the message to say something nicer (i.e. more specific to your application).

Upvotes: 1

Matthew Wilson
Matthew Wilson

Reputation: 2065

This will try to parse the url entered and retry until the user enters a valid url.

private static Scanner scanner;

public static void main(String[] args) {

    String input = readInput();
    boolean urlValid = false;
    URL url = null;
    while(!urlValid) {

        try {
            url = new URL(input);
            urlValid = true;
            System.out.println("The url was valid");
        } catch (MalformedURLException e) {
            System.out.println("The url was invalid, please try again");
            input = readInput();
        }
    }

    //continue processing
    System.out.println("The url entered was: "+url.toString());
}

private static String readInput() {
    System.out.println ("Enter a URL");
    scanner = new Scanner(System.in);
    return scanner.nextLine();
}

Upvotes: 0

Related Questions