习题4-6

参照4-18编写一个猜英文26个小写字母的web游戏

代码:

test4-6.jsp:相比于4-18的生成随机数字后用整型去保存运行,把产生随机字母的类型改成String字符串去进行保存和判断,将这个对象保存在session对象中,然后单击超链接请求guess.jsp页面。

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




猜数游戏


在26个英文小写字母中猜一个,请猜
<%  int num = (int)(Math.random()*25+97);
   /* 小写字母a-z的ASCII为97-122 */
   String word =String.valueOf((char) num); 
   session.setAttribute("count",new Integer(0));
   session.setAttribute("save",new String(word));
   %>
   
去猜测这个数

guess.jsp:通过调用一个Tag文件GuessTag.tag判断用户的猜测是否正确

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib tagdir="/WEB-INF/tags" prefix="guessnum" %>




猜数


<% String str=request.getParameter("guessnum");
   if(str==null) str="*";
   if(str.length()==0) str="*";
%>

当前猜测结果:<%= message %>
 <% if(message.startsWith("你猜对了")) {
   %>  
重新获取随机数 <%} else { %>
输入你的猜测:
<% } %>

GuessTag.tag:负责判断用户猜测的字母是否与存放的字符串相等

<%@ tag  pageEncoding="UTF-8"%>
<%@ attribute name = "number" required = "ture" %>
<%@ variable name-given="message" scope="AT_END" %>
 <%  String mess="";
    String str=(String)session.getAttribute("save");
    String str1=str.toString();
    boolean boo=true;
    if(number.equals("*")) {
    	boo = false;
    }
    if(boo){
    	if(number.equals(str1)){
    		int n=((Integer)session.getAttribute("count")).intValue();
    		n=n+1;
    		session.setAttribute("count",new Integer(n));
    		mess="猜对了,这是你的第"+n+"次猜测";
    	}
    	else {
    		int n=((Integer)session.getAttribute("count")).intValue();
    		n=n+1;
    		session.setAttribute("count",new Integer(n));
    		mess="猜错了,这是你的第"+n+"次猜测,请继续猜";
    	}
    	jspContext.setAttribute("message", mess);
    }
    else{
    	jspContext.setAttribute("message", "请输入你的猜测");
    }
    %>
 

运行结果:

习题4-6_第1张图片习题4-6_第2张图片习题4-6_第3张图片

习题4-6_第4张图片

你可能感兴趣的:(习题4-6)