使用JavaBean实现猜数游戏
package game; public class GuessNumber { //系统随机生成一个数 int answer=0; //用户猜的数 int guessNumber=0; //用户猜的次 数 int guessCount=0; String result=null; boolean right=false; public void setAnswer(int answer){ this.answer=answer; guessCount=0; } public int getAnswer(){ return answer; } public int getGuessNumber() { return guessNumber; } public void setGuessNumber(int guessNumber) { this.guessNumber = guessNumber; guessCount++; if(guessNumber==answer) { result="恭喜你猜对了!"; right=true; } else if(guessNumber>answer) { result="不好意思你猜大了!"; right=false; } else if(guessNumber<answer) { result="不好意思你猜小了!"; right=false; } else if(this.answer==-1||this.answer>100) { result="请输入1~100的整数!"; right=false; } } public int getGuessCount() { return guessCount; } public void setGuessCount(int guessCount) { this.guessCount = guessCount; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } public boolean isRight() { return right; } public void setRight(boolean right) { this.right = right; } }
<%//getNumber.jsp%>
<%@ page language="java" import="java.util.Random" pageEncoding="UTF-8"%> <%@ page contentType="text/html"%> <html> <head> <title>系统将随机生成一个数</title> <meta http-equiv="Content-Type" content="text/html;charset="utf-8"> </head> <body> <jsp:useBean id="guess" class="game.GuessNumber" scope="session"/> <% //实例化一个对象,该对象可以产生随机数 Random randomNumbers=new Random(); int answer=1+randomNumbers.nextInt(100); String str=response.encodeRedirectURL("guess.jsp"); %> <jsp:setProperty name="guess" property="answer" value="<%=answer%>"/> <h3>随系统随机生成了一个1到100之间的整数,请猜是什么数?</h3> <hr> <form action="<%=str%>"method="get"> 输入你猜的数:<input type="text"name="guessNumber"> <input type="submit"value="提交"> </form> </body> </html>
<%guess.jsp%> <%@ page contentType="text/html" pageEncoding="UTF-8"%> <html> <head> <title>猜的结果</title> <meta http-equiv="Content-Type" content="text/html;charset="utf-8"> </head> <body> <jsp:useBean id="guess" class="game.GuessNumber" scope="session"/> <% String strGuess=response.encodeRedirectURL("guess.jsp"); String strGetNumber=response.encodeRedirectURL("getNumber.jsp"); %> <hr> <jsp:setProperty name="guess" property="guessNumber" param="guessNumber"/> 这是第<jsp:getProperty name="guess" property="guessCount"/>次猜。 <jsp:getProperty name="guess" property="result"/> 你猜的数是<jsp:getProperty name="guess" property="guessNumber"/>。 <% if(guess.isRight()==false) {%> <form action="<%=strGuess%>"method="get"> 请再猜一次:<input type="text"name="guessNumber"> <input type="submit"value="提交"> </form> <% } %> <hr> <a href="<%=strGetNumber %>">重新开始猜数</a> </body> </html>