js| Note 1. This is a game of guessing numbers by using JSP to invoke JavaBean
2. Two documents required, NUMBER.JSP and Numberguessbean.java
3. First look at the number.jsp code:
<%
if (number.getnumguesses () ==0)
{
% >
Welcome to the number Guess game.
I ' m thinking of a number between 1 and.
What ' s your guess?
<%
}
Else if ( Number.getsuccess ())
{
% >
congratulations! You got it. And after just <%=number.getnumguesses ()%> tries.
Care to try again ?
<%
Number.reset ();
}
Else
{
% >
good guess, but nope. Try <%=number.gethint ()%>. You have made <%=number.getnumguesses ()%> guesses.
I ' m thinking of a number between 1 and 100.
What ' s your guess?
<%
}
% >
4. The Numberguessbean.java code is as follows:
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;
}
}