JSP Learning Notes (vii)-----guess number Game

Source: Internet
Author: User
Tags reset return string
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;
}
}





Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.