package com.myapp.struts;
/**
*
* @author
*/
import java.util.*;
public class GuessGame {
//私有成员,定义所需要的属性
int answer;
int guess;
boolean success;
String info;
int counter;
//构造函数,主要用于产生随机数
public GuessGame() {
reset();
}
//成员函数,设置和调用成员属性,完成游戏功能
public void setGuess(String guess) {
counter++;
//抛出异常
try {
this.guess = Integer.parseInt(guess);
}
catch (NumberFormatException e) {
this.guess = -1;
}
//判断所输入的数字与实际价格是否相同,或输入数字是否符合要求
if (this.guess == answer) {
success = true;
}
else if (this.guess == -1) {
info = "出错,再猜一次!";
}
else if (this.guess < answer) {
info = "您猜的价格小了!";
}
else if (this.guess > answer) {
info = "您猜的价格大了!";
}
//输入数字
if(this.guess >1000){
info="请输入1到1000之间的数字!!";
}
}
//返回值
public boolean getSuccess() {
return success;
}
//获得信息
public String getInfo() {
return info;
}
//获得计数器值
public int getCounter() {
return counter;
}
//获得答案
public int getAnswer(){
return answer;
}
//产生随机数,控制在1到1000之间
public void reset() {
answer = Math.abs(new Random().nextInt() % 1000) + 1;
success = false;
counter = 0;
}
}
====================
<%@ page contentType="text/html; charset=gb2312" %>
<%@ page import="com.myapp.struts.*" %>
<html>
<jsp:useBean id="game" class="com.myapp.struts.GuessGame" scope="session" />
<jsp:setProperty name="game" property="guess" />
<%
if(game.getCounter()==0)
{
%>
<center>
<font size=4 color=red>guess price</font>
<hr>
<p align="center"><img src="image/cake.jpg" alt="蛋糕" width="400" height="300" border=3></p>
<form method=get>
<b>input price:</b>
<input type=text name="guess">
<input type=submit value=确定>
</form></center>
<%
}
else if(game.getSuccess())
{
%>
<center><b>right, belong you。 you guess <%=game.getCounter()%> time(s).</b>
<br>
<a href=testGuest.jsp>once more?</a></center>
<%
game.reset();
}
else
{
%>
<center><b>
try again,
<%=game.getInfo()%>.
you have tried <%=game.getCounter()%> times.
<br>
input price:
<form method=get>
<input type=text name="guess">
<input type=submit value=b确定>
</form>
</b></center>
<%
}
%>
</html>