Software School Projects | Academic Students Projects | Source Codes | Tablets header
Please use our contact us form or send email to Support@srishtis.com.

The Number Guess Game by using JSP scriptlets and expressions

The file numguess.jsp is an interesting example of the use of scripting elements, because it is structured as you might structure a source file, with a large if ... else statement within scriptlet tags. The difference is that the body of each statement clause is written in HTML and JSP tags, rather than in a programming language.

You are not required to write scriptlets mingled with HTML and JSP tags, as shown in numguess.jsp. Between the <% and %> tags, you can write as many lines of scripting language code as you want. In general, doing less processing in scriptlets and more in components like servlets or Beans makes your application code more reusable and portable.

 
Displaying the Number Guess Screen (numguess.jsp) ________________________________________________________ <%@ page import = "num.NumberGuessBean" %>
<jsp:useBean id="numguess" class="num. NumberGuessBean" scope="session" />
<jsp:setProperty name="numguess" property="*" />
<html>
<head><title>Number Guess</title></head>
<body bgcolor="white">
<font size=4>
<% if (numguess.getSuccess() ) { %>
Congratulations! You got it.
And after just <%= numguess.getNumGuesses() %>
tries.<p>
<% numguess.reset(); %>
Care to <a href="numguess.jsp">try again</a>?
<% } else if (numguess.getNumGuesses() == 0) { %>
Welcome to the Number Guess game.<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>
<% } else { %>
Good guess, but nope. Try <b><%= numguess. getHint() %></b>.
You have made <%= numguess.getNumGuesses() %>
guesses. 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>
</body>
</html> __________________________________________________ Handling the Guess (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;
}
}
 
Job or extra money for students

Search Engine Rank of your blog or websites