設定一個1到100的數字,讓人去猜測,
每次猜完後告訴他猜的值比較大還是比較小
並告訴他已經猜了幾次
設定一個1到100的數字,讓人去猜測,
每次猜完後告訴他猜的值比較大還是比較小
並告訴他已經猜了幾次
一樣使用一個bean去存相關資料
=== numguess.jsp ===
<%@ page import = "num.NumberGuessBean" %>
<jsp:useBean id="numguess" class="num.NumberGuessBean" scope="session"/>
<jsp:setProperty name="numguess" property="*"/>
<title>Number Guess</title>
<body bgcolor="white">
<font size=4>
<% if (numguess.getSuccess()) { %>
Congratulations! You got it.
And after just <%= numguess.getNumGuesses() %> tries.<br>
<% numguess.reset(); %>
Care to <a href="numguess.jsp">try again</a>?
<% } else if (numguess.getNumGuesses() == 0) { %>
Welcome to the Number Guess game.<br>
I'm thinking of a number between 1 and 100.<br>
<form method=get action="numguess.jsp">
What's your guess? <input type=text name=guess>
<input type=submit value="Submit">
</form>
<% } else { %>
Good guess, but nope. Try <b><%= numguess.getHint() %></b>.
You have made <%= numguess.getNumGuesses() %> guesses.<p>
I'm thinking of a number between 1 and 100.<p>
<form method=get >
What's your guess? <input type=text name=guess>
<input type=submit value="Submit">
</form>
<% } %>
</font>
int answer 存正確答案
int numGuesses 存已猜了幾次
boolean success 存是否已猜中
String hint 存比較高,還是比較低
=== NumberGuessBean.java ===
package num;
import java.util.*;
public class NumberGuessBean {
int answer;
boolean success;
String hint;
int numGuesses;
public NumberGuessBean() {
reset();
}
public void setGuess(String guess) {
numGuesses++;
int g;
try {
g = Integer.parseInt(guess);
}
catch (NumberFormatException e) {
g = -1;
}
if (g == answer) {
success = true;
}
else if (g == -1) {
hint = "a number next time";
}
else if (g < answer) {
hint = "higher";
}
else if (g > answer) {
hint = "lower";
}
}
public boolean getSuccess() {
return success;
}
public String getHint() {
return "" + hint;
}
public int getNumGuesses() {
return numGuesses;
}
public void reset() {
answer = Math.abs(new Random().nextInt() % 100) + 1;
success = false;
numGuesses = 0;
}
}