jsp编写猜数字游戏

来源:互联网 发布:淘宝的专柜代购便宜 编辑:程序博客网 时间:2024/05/16 01:23

实现猜数字的小游戏。当客户访问服务器上的getNumber.jsp时,随机分配给客户一个1100之间的整数,然后将这个整数存在客户的session对象中。客户在表单里输入一个整数,来猜测分配给自己的那个整数。客户输入一个整数后,提交给result.jsp,该页面负责判断这个整数是否和客户session对象中存在的那个整数相同,如果相同就连接到success.jsp;如果不相同就连接到large.jspsmall.jsp,然后,客户在这些页面再重新提交整数result.jsp。


1、getNumber.jsp

<body>随机分给了你一个1到100之间的数,请猜!<%int number=(int)(Math.random()*100)+1;session.setAttribute("count", new Integer(0));session.setAttribute("save", new Integer(number));%>输入你所需猜的数<form action="Result.jsp" method="post" name=form><input type="text" name="boy"><input type="submit" value="提交" name="submit"></form></body>

2、Result.jsp

<body><%String str=request.getParameter("boy");if(str==null){str="0";}int guessNumber=Integer.parseInt(str);Integer integer=(Integer)session.getAttribute("save");int realnumber=integer.intValue();if(guessNumber==realnumber){int n=((Integer)session.getAttribute("count")).intValue();n=n+1;session.setAttribute("count", new Integer(n));response.sendRedirect("successjsp.jsp");}else if(guessNumber>realnumber){int n=((Integer)session.getAttribute("count")).intValue();n=n+1;session.setAttribute("count", new Integer(n));response.sendRedirect("large.jsp");}else if(guessNumber<realnumber){int n=((Integer)session.getAttribute("count")).intValue();n=n+1;session.setAttribute("count", new Integer(n));response.sendRedirect("small.jsp");}%></body>

3、large.jsp

<body>所猜的数比实际的大,请再猜:<form action="Result.jsp" method="get" name=form><input type="text" name="boy"><input type="submit" value="提交" name="submit"></form><%Integer integer=(Integer)session.getAttribute("save");int realnumber=integer.intValue();out.println(realnumber);%></body>


4、small.jsp

<body>所猜的数比实际的小,请再猜:<form action="Result.jsp" method="post" name=form><input type="text" name="boy"><input type="submit" value="提交" name="submit"></form><%Integer integer=(Integer)session.getAttribute("save");int realnumber=integer.intValue();out.println(realnumber);%></body>

5、successjsp.jsp

<body><%int count=((Integer)session.getAttribute("count")).intValue();int num=((Integer)session.getAttribute("save")).intValue();long startTime=session.getCreationTime();long endTime=session.getLastAccessedTime();%>恭喜你,猜对了您共猜了<%=count%>次用时<%=(endTime-startTime)/1000 %>秒这个数字就是<%=num %>你必须关闭浏览器,才能获得新的数。</body>


注意事项:

1、文中在猜完第一次后,为了方便测试打印出了产生的随机数,读者可以在代码中去除。

2、注意代码上action跳转的页面要和自己新建的jsp页面名称一致。

0 0