用JSP做一个简单的猜数游戏

首页 start.jsp
<?xml version="1.0" encoding="UTF-8" ?>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Insert title here</title>
</head>
<body>
<form name="fo" mothod="post" action="chuli.jsp">
<h1>猜数游戏</h1>
<h3>请输入1到100的数字:</h3>
<input type="text" name="text">
<script language="javascript"> document.fo.text.focus();</script>
<input type="submit" name="submit" value="提交">
<%
String error=(String)request.getAttribute("bag");
String rige=(String)request.getAttribute("ww");
String fger=(String)request.getAttribute("noter");

if(error!=null){%>
<table><tr><td><%=error %></td></tr></table>
<%}
if(rige!=null){
%>
<table><tr><td><%=rige%></td></tr></table>
<%
}
if(fger!=null){

%>
<table><tr><td><%=fger %></td></tr></table>
<%
}
%>
</body>
</html>

第二个页面 chuli.jsp


<?xml version="1.0" encoding="UTF-8" ?>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Insert title here</title>
</head>
<body>
<%!
int randoma=0;
int coun=0;
int ie=0;
%>
<%
try{
String str=request.getParameter("text");
int n=Integer.parseInt(str);

if(ie==0)
{
   randoma=(int)(Math.random()*100)+1;
    ie++;
}

     System.out.println("随机"+randoma);//测试*********
     System.out.println("猜数"+n);
    
     if(n>randoma){
       request.setAttribute("bag","您猜的数大了");
       coun++;   
       String connn="您猜了"+coun+"次";
       request.setAttribute("ww",connn);      
       pageContext.forward("start.jsp");      
     }
     if(n<randoma){
     request.setAttribute("bag","您猜的数小了");
     coun++;
     String connn="您猜了"+coun+"次";
     request.setAttribute("ww",connn);    
     pageContext.forward("start.jsp");
       
    }
     if(n==randoma){
 
     coun++;
     String connn="您猜了"+coun+"次";
     request.setAttribute("ww",connn);
     ie=0;
     coun=0;
    %>
 
    <h1>恭喜你猜对了!!!</h1>
    <img src="imag/q.gif">
    <h3>你还想<a href="start.jsp">再来一次</a>吗?</h3>
   
    <%
   }
    
}catch(NumberFormatException e)
{
request.setAttribute("noter", "您输入的不合法请重新输入");
  pageContext.forward("start.jsp");
}
%>
</body>
</html>




你可能感兴趣的:(游戏,jsp,xml,XHTML,IE)