Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Intro Java Question: Write a Java class called MyUrl that represents a URL (Unif

ID: 3756974 • Letter: I

Question

Intro Java Question:

Write a Java class called MyUrl that represents a URL (Uniform Resource Locator) with optional URL encoded parameters attached. It should have a private String instance variable representing the URL, and have the following public methods:

public MyUrl(String url) - this constructor initializes the base URL to the url parameter value. It adds the protocol prefix http:// on the front if not present in the url parameter.. For example, if the parameter is www.amazon.com, it sets the mUrl instance variable to http://www.amazon.com  Note that a constructor has no return type, not even 'void'.

public void addArgument(String name, String value) - this overloaded method adds a string argument to the URL of the form name=value. It URL encodes both the name and value parameters by calling the urlEncode() method on each.

public void addArgument(String name, int ivalue) - this overloaded method adds an int argument to the URL of the form name=value. It URL encodes the name parameter by calling urlEncode().. The value is the string representation of the ivalue parameter. Use Integer.toString(ivalue) to convert the integer to a string representation.

public void addArgument(String name, double dvalue) - this overloaded method adds a double argument to the URL of the form name=value. It URL encodes the name parameter by calling urlEncode().. The value is the string representation of the dvalue parameter. Use Double.toString(dvalue) to convert the double to a string representation.

public String toString() - this method returns the object's URL value (the base URL plus all arguments).

public static String urlEncode(String text) - this static method URL encodes its parameter String and returns the URL encoded value as the result. It is called by the addArgument methods to encode their name and value parameters before appending them to the object's URL. Use your earlier project code to implement this method - instead of reading a line of text, the parameter string contains the text to be URL encoded, and instead of printing the encoded string, it is returned as the method result.

Arguments are added to the URL as name=value, where name and value are URL encoded. If any arguments are present in a URL, a '?' precedes the first name=value, with subsequent arguments separated by '&' characters. For example, a URL of www.amazon.com with a first argument name of id and value of 123 and a second argument name of author and value of Jim Campbell would look like:

http://www.amazon.com?id=123&author=Jim+Campbell

In order to determine whether to use a "?" or "&" when appending an argument, you'll either need to look at the current URL value to see if it already contains a "?", or use a counter instance variable that contains the number of arguments appended to the object's URL.

Note: the main() method for testing this class is supplied for you at a link at the bottom of this page. Do NOT write your own main() method, the main method codes is provided at the end in the MyUrlDemo.java.

Sample Output should be like below:

Enter URL site (or 'exit')...
www.amazon.com
Url value read was: www.amazon.com
Enter URL argument name (or 'done')...
id
Enter type of argument value (string, integer, double)...
integer
Enter an integer value
123
Enter URL argument name (or 'done')...
author
Enter type of argument value (string, integer, double)...
string
Enter a string value
Jim Campbell
Enter URL argument name (or 'done')...
publisher
Enter type of argument value (string, integer, double)...
string
Enter a string value
O'Reilly
Enter URL argument name (or 'done')...
done
URL with appended arguments is:
  http://www.amazon.com?id=123&author=Jim+Campbell&publisher=O%27Reilly

Enter URL site (or 'exit')...
exit

Test Data

Use the following test data, plus an example of your own. The example name and value arguments below should be entered as two separate inputs as shown in the sample output above.

base url: www.boston.com
   (no arguments)

base url: http://www.google.com
   (no arguments)

base url:  www.barnesandnoble.com
  name: publisher
  value: Addison & Wesley
  name: title
  value: Does e=mc2 ?
  name: price
  value: 19.95

base url:  http://www.amazon.com
  name: published
  value: 6/2010
  name: title
  value: History of M & M's
  name: SKU#
  value: 12345

Test Code

Use the MyUrlDemo.java source codes below.

The MyUrlDemo.java file contains just the supplied main() method test code. Compile your MyUrl.java file first, then the MyUrlDemo.java file next. Make sure to provide approriate comments for your codes in the MyUrl.java file.

Use this to test your MyUrl.java:

Explanation / Answer

MyUrlDemo.java
import java.util.Scanner;
public class MyUrlDemo
{

    /**
     * main
     */
    public static void main (String[] args)
    {
        Scanner sc = new Scanner(System.in);

        // Loop, asking for a new URL to be entered.
        do {
            System.out.println();
            System.out.println("Enter URL site (or 'exit')...");
            String baseUrl = sc.nextLine();
            if (baseUrl.equalsIgnoreCase("exit"))
                break;

            // Create a new MyUrl object and call its constructor
            MyUrl u = new MyUrl(baseUrl);
            System.out.println("Url value read was: " + baseUrl);

            // Loop, asking for argument/value input
            do {
                System.out.println("Enter URL argument name (or 'done')...");
                String argName = sc.nextLine();
                if (argName.equalsIgnoreCase("done"))
                    break;
                System.out.println("Enter type of argument value (string, integer, double)...");
                String argType = sc.nextLine();

                if (argType.startsWith("s")) {
                    System.out.println("Enter a string value");
                    String s = sc.nextLine();
                    u.addArgument(argName, s);
                } else if (argType.startsWith("i")) {
                    System.out.println("Enter an integer value");
                    int i = sc.nextInt();
                    sc.nextLine();
                    u.addArgument(argName, i);
                } else if (argType.startsWith("d")) {
                    System.out.println("Enter a double value");
                    double d = sc.nextDouble();
                    sc.nextLine();
                    u.addArgument(argName, d);
                } else {
                    System.out.println("Unrecognized value type - must be (s)tring, (i)nteger, or (d)ouble");
                    continue;
                }
            }while (true);

            // Display the final url
            System.out.println("URL with appended arguments is:");
            System.out.println(" " + u.toString());

        } while (true);

        // Keep console window alive until 'enter' pressed (if needed).
        System.out.println();
        System.out.println("Done - press enter key to end program");
        String junk = sc.nextLine();
    }
}


MyUrl.java

public class MyUrl {
   private String mUrl;
   private int counter;
  
   public MyUrl(String url){
   //initialize base URL to url parameter
       // add the protocol prefix if not present http://
       if(url.startsWith("http") != true){
           mUrl = "http://" + url;
       }
       else
           mUrl = url;
   }
   public void addArgument(String name, String value){
   // add a string argument ot the URL of the form name = value
       // url encode both the name and the value params by calling urlEncode() on each
       ++counter;
      
       if(counter == 1)
           mUrl = mUrl + "?";
       else
           mUrl = mUrl + "&";
      
       String encName, encValue;
       encName = urlEncode(name);
       encValue = urlEncode(value);
       mUrl = mUrl + encName + "=" + encValue;
   }
   public void addArgument(String name, int ivalue){
   // add an int argument to the URL of the form name = value
       // URL encode the name param by calling urlEncode()
       // the value is the string representation of the ivalue param
       // use Integer.toString(ivalue) to convert the int to a string representation
       ++counter;
      
       if(counter == 1)
           mUrl = mUrl + "?";
       else
           mUrl = mUrl + "&";
      
       String encName, encIvalue;
       encName = urlEncode(name);
       encIvalue = Integer.toString(ivalue);
       mUrl = mUrl + encName + "=" + encIvalue;
   }
  
   public void addArgument(String name, double dvalue){
       // add a double argument to the URL of the form name = value
       // URL encode the name param by calling urlEncode()
       // the value is the string representation of the dvalue param
       // use Double.toString(ivalue) to convert the double to a string representation
       ++counter;
      
       if(counter == 1)
           mUrl = mUrl + "?";
       else
           mUrl = mUrl + "&";
      
       String encName, encDvalue;
       encName = urlEncode(name);
       encDvalue = Double.toString(dvalue);
       mUrl = mUrl + encName + "=" + encDvalue;
   }
  
   public String toString(){
   // returns the object's URL value (base URL plus all arguments)
       return mUrl;
   }
   public static String urlEncode(String text){
   // static method URL encodes its parameter String and returns the URL encoded value as result
       // called by the addArgument methods to encode their name and value params before
       // appending them to the URL
       String encOutput = "";
       int lengthOfLine = text.length();
      
       for(int i = 0; i < lengthOfLine; i++)
    {
      char lineChar = text.charAt(i);

      if(lineChar == ' ')
        encOutput += '+';
      else if(Character.isLetterOrDigit(lineChar) || lineChar == '_'
              || lineChar == '-' || lineChar == '.' || lineChar == '*')
        encOutput += lineChar;
      else{
        encOutput += '%' + Integer.toHexString(lineChar);
      }
    }
       return encOutput;
   }
  
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote