<%@ page language= "java " %>
<%@ page session= "true " %>
<%@ page contentType= "text/html;charser=gb2312 "%>
<%@ page import= "java.lang.* "%>
<%@ page import= "java.util.* "%>
<%!
public String getMessage(int[] result){
switch(result[0]){
case -2:return "san wei shu ";
case -1:return "ge shi wrong! ";
case 0:return "right ";
default :return "go on! ";
}
}
public int[] checkNumber(String guessnum,String answernum){
if(guessnum.length()!=3)
return new int[]{-2,0,0};
int num=0;
try{
num=Integer.parseInt(guessnum);
}catch(NumberFormatException e){
return new int[]{-1,0,0};
}
int a=0;
int b=0;
for(int j=0;j <3;j++){
int pos=answernum.indexOf(guessnum.substring(j,j+1));
if(pos==j)
a++;
else if(pos> =0)
b++;
}
if(a==3)
return new int[]{0,a,b};
else
return new int[]{1,a,b};
}
%>
<%
Vector history=(Vector)session.getValue( "HISTORY ");
String answernum=(String)session.getValue( "ANSWER ");
String guessnum=null;
String message=null;
boolean gameover=false;
if(history==null||answernum==null){
history=new Vector();
answernum= "456 ";
session.putValue( "HISTORY ",history);
session.putValue( "ANSWER ",answernum);
}else{
guessnum=request.getParameter( "guess_number ");
int[] result=checkNumber(guessnum,answernum);
message=getMessage(result)+ "ni cai de shi "+guessnum;
if(result[0]==0)
gameover=true;
else if(history.size()> =4){
gameover=true;
message+= "answer: "+answernum;
}
history.insertElementAt(message,0);
session.putValue( "ANSWER ",answernum);
}
if(gameover){
session.removeValue( "HISTORY ");
session.removeValue( "ANSWER ");
}
%>
<html>
<title>
a example of session
</title>
<body bgcolor= "#ffffff ">
<h1> cai shu zi! </h1>
<form name= "form1 " method= "get " action= "numguess1.jsp ">
number: <input type= "text " name= "guess_number " size= "4 " maxlength= "4 ">
<input type= "submit " name= "submit " value= "enter ">
</form>
<%
int i=history.size();
for(Enumeration e=history.elements();e.hasMoreElements();){
%>
<%=i%> , <%=(String)e.nextElement()%> <br>
<%
i--;
}
if(gameover){
%>
<form name= "form2 " method= "get " action= "numguess1.jsp ">
<input type= "submit " name= "submit " value= "go on ">
</form>
<%