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

Debug this Java code. Please comment the errors in the code. import java.io.*; i

ID: 644328 • Letter: D

Question

Debug this Java code. Please comment the errors in the code.

import java.io.*;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.*;

/* Creates or appends to the end of a test random

* access file and then reads back

* everything in the random acccess file.

*

*/

@WebServlet(name = "DebugW4", urlPatterns = { "/debugW4" })

public class debugW4 extends HttpServlet {

    private RandomAccessFile randomAF;

    private final String TEST_PHRASE = " My random access file ";

    protected void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        try (PrintWriter out = response.getWriter()) {

            out.println("<!DOCTYPE html>");

            out.println("<html><head><title>Servlet debugW4</title></head>");        

            out.println("<body><h1> Test writing and reading on a random access file </h1><p>");

            out.println(testRAF());

            out.println("</p></body></html>");

        }

    }

   

    // Every time this is executed it should append the TEST_PHRASE to the end of

    // the file and read back the entire file.

    private String testRAF() throws IOException{

        String data;

        StringBuilder sb = new StringBuilder();

        randomAF = new RandomAccessFile("test.dat", "r");

        randomAF.seek(randomAF.length());

        randomAF.writeChar(TEST_PHRASE);

        randomAF.seek(0);

        while ((data = randomAF.readLine()) == null){

            sb.append(data);  

        }

        randomAF.close();

        return sb.toString();

    }

}

Explanation / Answer

Compilation Errors Detected

Line: 3
package javax.servlet.annotation does not exist

need Tomcat 7.0 with a web.xml declared conform Servlet 3.0. Otherwise just live with<servlet> stuff in web.xml. See also stackoverflow.com/tags/servlets/info

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