1. This is a game of guessing numbers. By using JSP to call JavaBean
2. Two files are required: Number. jsp and numberguessbean. java.
3. Check the number. JSP code first:
<HTML>
<JSP: usebean id = "Number" class = "numberguessbean" Scope = "session"/>
<JSP: setproperty name = "Number" property = "*"/>
<%
If (number. getnumguesses () = 0)
{
%>
<B> welcome to the number guess game. </B>
<Br>
<B> I'm thinking of a number between 1 and 100. </B>
<Br>
<B> what's your guess? </B>
<Form method = post>
<Input type = text name = "Guess">
<Input type = submit value = submit>
</Form>
<%
}
Else if (number. getsuccess ())
{
%>
Congratulations! You got it. And after just <% = number. getnumguesses () %> tries.
Care to <a href = number. jsp> try again </a>?
<%
Number. Reset ();
}
Else
{
%>
Good guess, but nope. Try <% = number. gethint () %>. You have made <% = number. getnumguesses () %> guesses.
<Br> I'm thinking of a number between 1 and 100.
<Br>
What's your guess?
<Form method = post> <input type = text name = "Guess">
<Input type = submit value = submit>
</Form>
<%
}
%>
</Html>
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;
}
}