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

In Internet programming, programmers receive parameters via a query string, whic

ID: 3681822 • Letter: I

Question

In Internet programming, programmers receive parameters via a query string,
which looks like a String with fields separated by the "&" character. Each field typically has metadata part and
a data part separated by the equal sign. An example of a query string is :
first=Mike&last=Jones&id=mike1&password=hello

Using Scanner at least once, parse a query string like that above and output each field on a different line,
replacing the = sign with a colon followed by a space. For example, the output for the preceding sample
query string should look like:

first: Mike
last: Jones
id: mike1
password: hello

You can add more difficulty by putting the query string in a file and read it from the file. It is also
acceptable to simply create a variable called queryString and initialize it to a string similar to the example given above.

Explanation / Answer

import java.io.File;
import java.util.Scanner;

/**
* @author Srinivas Palli
*
*/
public class ReadQueryString {

   /**
   * @param args
   */
   public static void main(String[] args) {
       Scanner scanner1 = null, scanner2 = null;
       try {
           scanner1 = new Scanner(new File("input.txt"));
           while (scanner1.hasNext()) {

               String line = scanner1.nextLine();
               System.out.println(line);
               scanner2 = new Scanner(line);
               scanner2.useDelimiter("&");
               while (scanner2.hasNext()) {
                   String paramVal = scanner2.next().replace("=", ":");
                   System.out.println(paramVal);
               }
           }

       } catch (Exception e) {
           // TODO: handle exception
       } finally {

           scanner1.close();
           scanner2.close();
       }
   }
}

input.txt

first=Mike&last=Jones&id=mike1&password=hello

OUTPUT:

first=Mike&last=Jones&id=mike1&password=hello
first:Mike
last:Jones
id:mike1
password:hello

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