Hide
Know what you're getting – Unlike many sites, all our code is clearly licensed. Join Siafoo Now or Learn More

Fibonacci Number Servlet Atom Feed 0

In Brief A simple servlet that will return the fibbonaci number with the provided index. I wrote this for the Google I/O contest a few months back.
# 's
 1import java.io.IOException;
2import java.io.PrintWriter;
3
4import javax.servlet.http.*;
5
6@SuppressWarnings("serial")
7public class FibioServlet extends HttpServlet {
8 public void doGet(HttpServletRequest req, HttpServletResponse resp)
9 throws IOException {
10 resp.setContentType("text/plain");
11
12 PrintWriter w = resp.getWriter();
13
14 String input = req.getParameter("input");
15
16 if((input == null) || (input.length() == 0)){
17 w.println("{\"exception\":\"no input\"}");
18 return;
19 }
20
21 try
22 {
23 // the String to int conversion happens here
24 int in = Integer.parseInt(input);
25 int result = 0;
26
27 if(in <= 1){
28 result = in;
29 }else{
30 int[] fibs = new int[in + 1];
31
32 fibs[0] = 0;
33 fibs[1] = 1;
34
35 for(int i = 2; i < in + 1; ++i){
36 fibs[i] = fibs[i - 1] + fibs[i - 2];
37 }
38 result = fibs[in];
39 }
40 // print out the value after the conversion
41 w.println("{\"result\":" + result + "}");
42 }
43 catch (NumberFormatException nfe)
44 {
45 w.println("{\"exception\":" + nfe.getMessage() + "}");
46 }
47
48 }
49}

A simple servlet that will return the fibbonaci number with the provided index. I wrote this for the Google I/O contest a few months back.