Question

In: Computer Science

Java Prorgramming Skills Looping Branching Use of the length(), indexOf(), and charAt() methods of class String...

Java Prorgramming


Skills

  • Looping
  • Branching
  • Use of the length(), indexOf(), and charAt() methods of class String
  • Use of the static Integer.toHexString method to convert a character to its ASCII hex value

Description

In this assignment, you'll be URL encoding of a line of text. Web browsers URL encode certain values when sending information in requests to web servers (URL stands for Uniform Resource Locator).

Your program needs to perform the following steps:

  1. Prompt for a line of input to be URL encoded
  2. Read the line of text into a String (using the Scanner class nextLine method)
  3. Print the line that was read.
  4. Print the number of characters in the line (using String.length)
  5. Create an output String that is the URL encoded version of the input line (see below for details on encoding).
  6. Print the URL encoded String
  7. Print the number of characters in the encoded String.

To convert a String to URL encoded format, each character is examined in turn:

  • The ASCII characters 'a' through 'z', 'A' through 'Z', '0' through '9', '_' (underscore), '-' (dash), '.' (dot), and '*' (asterisk) remain the same.
  • The space (blank) character ' ' is converted into a plus sign '+'.
  • All other characters are converted into the 3-character string "%xy", where xy is the two-digit hexadecimal representation of the lower 8-bits of the character.

Use a for loop which increments it's index variable from 0 up to the last character position in the input string. Each iteration of the loop retrieves the character at the 'index' position of the input string (call the String class charAt() method on the input string). Use if statements to test the value of the character to see if it needs to be encoded. If encoding is not required, just concatenate it to the output encoded String. If encoding is required, concatenate the encoded value to the output encoded String. For example, if the input character is a blank, you want to concatenate a '+' character to the output encoded String (as described above).

Note: one technique to determine if a character is one that remains the same is to first create an initialized String containing all of the letters (both upper and lower case), digits, and other special characters that remain the same as described above. Then, call the String indexOf method on that String, passing the character to be tested. If -1 is returned from indexOf, the character was not one of those that remains the same when URL encoding.

For those characters that need to be converted into hex format (%xy above), you can call the pre-defined static Integer.toHexString method, passing the character as an argument. It returns the hex value of the character as a String, which you can concatenate to the encoded output String with the accompanying '%' symbol:

    String hexValue = Integer.toHexString(srcChar);
    encodedLine += '%' + hexValue;

Values that are URL encoded in this manner can be URL decoded by reversing the process. This is typically done by a web server upon receiving a request from a browser.

Sample Output

Enter a line of text to be URL encoded
This should have plus symbols for blanks

The string read is: This should have plus symbols for blanks
Length in chars is: 40
The encoded string: This+should+have+plus+symbols+for+blanks
Length in chars is: 40

Enter a line of text to be URL encoded
This should have hex 2f for /

The string read is: This should have hex 2f for /
Length in chars is: 29
The encoded string: This+should+have+hex+2f+for+%2f
Length in chars is: 31

Test Data

Use all the following test data to test your program, plus an example of your own:

This should have hex 2f for /
An encoded + should be hex 2b
123 and _-.* are unchanged
Angles, equals, question, ampersand > < = ? &

Getting started

Before you start writing Java code, it's usually a good idea to 'outline' the logic you're trying to implement first. Once you've determined the logic needed, then start writing Java code. Implement it incrementally, getting something compiled and working as soon as possible, then add new code to already working code. If something breaks, you'll know to look at the code you just added as the likely culprit.

To help you get started with this homework, here's an outline of the logic you'll need (sometime referred to as 'pseudo-code'):

Prompt for the line of input.
Read a line into the input string.

Set the encoded output string to empty.
Loop through each character in the input string.
{
Get the n'th character from the input string (use String's charAt method).

if (the character is a blank)
    concatenate '+' to the encoded output string
else if (the character remains unchanged)
    concatenate the character to the encoded output string
else
    concatenate '%' and the hex encoded character value
    to the encoded output string
}

Print the encoded output string.

Once you understand this logic, start writing your Java code. An example of the steps you could take are as follows:

  1. Create your Java source file with the public class and main() method (like homework 1).
  2. In the main() method, add code to prompt for the input line, read in the line of input, and print it out.
  3. Next, add the for-loop that loops through each character of the input string. You can use the length() method on your input string to get the number of characters in it to control your loop.
  4. The first statement in the loop should call charAt() on the input string to get the next character to examine.
  5. To check things are working ok so far, make the next statement in the loop print out the character position (the for-loop index variable) and character from the string.
  6. Get this much compiled and running first.

With this much done, if you read in a line containing "hello", you'd get output something like this from the temporary output statement within the loop:

char 0 is h
char 1 is e
char 2 is l
char 3 is l
char 4 is o

Once you've got this compiled and working, starting adding the if/else-if/else logic inside the loop to build the encoded output string.

I have this so far.What am I doing wrong here,please let me know. The code has to fit this requirement.

For those characters that need to be converted into hex format (%xy above), you can call the pre-defined static Integer.toHexString method, passing the character as an argument. It returns the hex value of the character as a String, which you can concatenate to the encoded output String with the accompanying '%' symbol:

    String hexValue = Integer.toHexString(srcChar);
    encodedLine += '%' + hexValue;

Values that are URL encoded in this manner can be URL decoded by reversing the process. This is typically done by a web server upon receiving a request from a browser.

I don't how to fit the last requirement

here is my code so far

import java.util.Scanner;

   public class URLEncoding {

       public static final String Notencodedchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~*'()"; }
  
      
       public static void main1(String args[]) {
           System.out.println("Enter a line of text to be URL encoded");
   // Create a scanner to read from keyboard
@SuppressWarnings("resource")
   Scanner sc = new Scanner (System.in);
String input = sc.nextLine();
System.out.println("The String read is :");
System.out.println("Length in chars is: "+input.length());
String Encoded ="";
char c;
for (int indexOf = 0; indexOf < input.length(); indexOf ++) {
  
       char ch = input.charAt(indexOf);
       if(Notencodedchars.indexOf(c) != -1)
               {
  
              
               Encoded += c;
               }
               else
               {
               if(c == ' ')
               //Encoded.concat("+");
               Encoded += '+';
               else
               {
                   public static String toHexString(int i) {
                   return toUnsignedString0(i, 4);
                   }
               private static String toUnsignedString0(int i, int j) {
                           // TODO Auto-generated method stub
                           return null;
                       }
                   String hexValue = Integer.toHexString(srcChar);
               encodedLine += '%' + hexValue;
               }
               }
       System.out.println("The encoded string is :"+ encodedString.toString());

       System.out.println("Length in chars is :" + encodedString.toString().length());

       }

       }


Someone ,please correct this for me.

Solutions

Expert Solution

************* URLEncoding.java *************

import java.util.Scanner;

public class URLEncoding {

   public static final String Notencodedchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~*'()";

   public static void main(String args[]) {
       System.out.println("Enter a line of text to be URL encoded");
       // Create a scanner to read from keyboard
       @SuppressWarnings("resource")
       Scanner sc = new Scanner(System.in);
       String input = sc.nextLine();
       System.out.println("The String read is :");
       System.out.println("Length in chars is: " + input.length());
       String Encoded = "";
       for (int indexOf = 0; indexOf < input.length(); indexOf++) {
           // This line will pick one character per loop
           char ch = input.charAt(indexOf);
           if (Notencodedchars.indexOf(ch) != -1) {
               Encoded += ch;
           } else if (ch == ' ')
               // Encoded.concat("+");
               Encoded += '+';
           else {
               String hexValue = Integer.toHexString(ch);
               Encoded += '%' + hexValue;
           }
       }
       System.out.println("The encoded string is :" + Encoded.toString());
       System.out.println("Length in chars is :" + Encoded.toString().length());
   }

}


############ Sample output ###############


Related Solutions

In the following Java class, what would the following createFromString(String string) and saveToString() methods return? /**...
In the following Java class, what would the following createFromString(String string) and saveToString() methods return? /** * This class represents a DVD player to be rented. * * @author Franklin University * @version 2.0 */ public class DVDPlayer extends AbstractItem { /** * Constructor for objects of class DVDPlayer. */ public DVDPlayer() { // No code needed } /** * Creates a DVDPlayer from a string in the format * id:desc:weeklyRate:rented * @param string The string * @return the new...
**** All these methods should be implemented using RECURSIVE solutions (no looping statements) // Java //...
**** All these methods should be implemented using RECURSIVE solutions (no looping statements) // Java // This method takes an integer array as well as an integer (the starting // index) and returns the sum of the squares of the elements in the array. // This method uses recursion. public int sumSquaresRec(int[] A, int pos) { // TODO: implement this method        return -1; // replace this statement with your own return }    // This method takes a...
(USE C ++ AND class STRING ONLY!!!! No java, No cstring and No vector) Write a...
(USE C ++ AND class STRING ONLY!!!! No java, No cstring and No vector) Write a program that can be used to train the user to use less sexist language by suggesting alternative versions of sentences given by the user. The program will ask for a sentence, read the sentence into a string variable, and replace all occurrences of masculine pronouns with genderneutral pronouns. For example, it will replace "he" with "she or he". Thus, the input sentence See an...
java Objective: Create a class. Create objects. Use methods of a class. Create a class BankAccount...
java Objective: Create a class. Create objects. Use methods of a class. Create a class BankAccount to represent a bank account according to the following requirements: A bank account has three attributes: accountnumber, balance and customer name. Add a constructor without parameters. In the initialization of the attributes, set the number and the balance to zero and the customer name to an empty string. Add a constructor with three parameters to initialize all the attributes by specific values. Add a...
Code in Java Given the LinkedList class that is shown below Add the following methods: add(String...
Code in Java Given the LinkedList class that is shown below Add the following methods: add(String new_word): Adds a linkedlist item at the end of the linkedlist print(): Prints all the words inside of the linkedlist length(): Returns an int with the length of items in the linkedlist remove(int index): removes item at specified index itemAt(int index): returns LinkedList item at the index in the linkedlist public class MyLinkedList { private String name; private MyLinkedList next; public MyLinkedList(String n) {...
Which of this method of class String is used to obtain a length of String object?...
Which of this method of class String is used to obtain a length of String object? What is the output of the below Java program with WHILE, BREAK and CONTINUE? int cnt=0; while(true) { if(cnt > 4)    break;    if(cnt==0) {     cnt++; continue; }   System.out.print(cnt + ",");   cnt++; } 1,2,3,4 Compiler error 0,1,2,3,4, 1,2,3,4,
In Java, Here is a basic Name class. class Name { private String first; private String...
In Java, Here is a basic Name class. class Name { private String first; private String last; public Name(String first, String last) { this.first = first; this.last = last; } public boolean equals(Name other) { return this.first.equals(other.first) && this.last.equals(other.last); } } Assume we have a program (in another file) that uses this class. As part of the program, we need to write a method with the following header: public static boolean exists(Name[] names, int numNames, Name name) The goal of...
Use Java programming to implement the following: Implement the following methods in the UnorderedList class for...
Use Java programming to implement the following: Implement the following methods in the UnorderedList class for managing a singly linked list that cannot contain duplicates. Default constructor Create an empty list i.e., head is null. boolean insert(int data) Insert the given data into the end of the list. If the insertion is successful, the function returns true; otherwise, returns false. boolean delete(int data) Delete the node that contains the given data from the list. If the deletion is successful, the...
In Java: Design a class that checks if a String is made of tokens of the...
In Java: Design a class that checks if a String is made of tokens of the same data type (for this, you may only consider four data types: boolean, int, double, or char). This class has two instance variables: the String of data and its delimiter. Other than the constructor, you should include a method, checkTokens, that takes one parameter, representing the data type expected (for example, 0 could represent boolean, 1 could represent int, 2 could represent double, and...
java programing Q: Given the following class: public class Student { private String firstName; private String...
java programing Q: Given the following class: public class Student { private String firstName; private String lastName; private int age; private University university; public Student(String firstName, String lastName, int age, University university) { this.firstName = fisrtName; this.lastName = lastName; this.age = age; this.university = university; } public String getFirstName(){ return firstName; } public String getLastName(){ return lastName; } public int getAge(){ return age; } public University getUniversity(){ return university; } public String toString() { return "\nFirst name:" + firstName +...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT