Number guesser game generates a different numbers each guess - java

I have a Java Server Page that lets the user pick a number of their choice from 1-1000. The page then uses the number entered and finds out if the number matches the number that is generated. -- Pictures below if ^ is unclear. Currently, the program generates a different number each time the user guesses a number -- whether it is correct or not. How do I make it so that the program only generates a number when the user either refreshes the page or guesses correctly?
JSP code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# page import = "Chapter12.RandomGuess" %>
<jsp:useBean id = "randomGuessId" class = "Chapter12.RandomGuess" scope = "page" >
</jsp:useBean>
<jsp:setProperty name = "randomGuessId" property = "*" />
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Guess Random Number</title>
</head>
<body>
<h3>Guess a number from 1 to 1000</h3>
<form method = "post">
Enter guess: <input name = "guess" /><br /><br />
<input type = "submit" name = "Submit" value = "Take Guess" />
<input type = "reset" value = "Reset" /><br /><br />
Your guess of <jsp:getProperty name = "randomGuessId" property="guess" />
is <%= RandomGuess.guess(randomGuessId.getAnswer()) %>
</form>
</body>
</html>
Java code:
import java.util.Random;
public class RandomGuess {
private int guess;
Random r = new Random();
private int low = 1;
private int high = 1000;
int R = r.nextInt(high-low) + low;
public int getGuess() {
return guess;
}
public void setGuess(int newValue) {
guess = newValue;
}
public String getAnswer() {
String tooLow = "too low.";
String tooHigh = "too high.";
String correct = "correct!";
if(guess == R)
return correct;
else if(guess < R)
return tooLow;
else
return tooHigh;
}
public static String guess(String s) {
return s;
}
}
picture: http://i.imgur.com/dMSZ7SD.png

Every time the page refreshes, a new instance of the bean is created - with a new number.
To preserve the number across calls, use a static field in your class.
Better yet, use JavaScript!

Find complete program here:http://sickprogrammersarea.blogspot.in/2014/01/creating-number-guesser-in-jsp_8296.html
Hello friends this is a simple program of creating a number guesser in JSP....Have a look...
Number.jsp:
<html>
<head><title>Number Guesser</title></head>
<body>
<% int num=(int)(Math.random()*100); %>
<h2>Welcome To Number Guesser</h2>
<br><h3>Want To Check Your Guessing Power.....GIVE IT A TRY?????</h3>
<form name="guess" action="try.jsp?c=0" method="post">
<input type="text" name="val" value="<%=num %>" hidden>
<input type="submit" value="GO">
</form>
</body>
</html>
try.jsp :
<html>
<head><title>Number Guesser</title></head>
<body>
<% String str=request.getParameter("val");
boolean flag=true;
int num=Integer.parseInt(str);
int c=Integer.parseInt(request.getParameter("c"));
if(c!=0)
{
int guess=Integer.parseInt(request.getParameter("guess"));
if(num==guess){
flag=false;
%>
<h3>Congratulation...You Successes After <%=c%> attempts</h3>
<b>Want to Improve...try again</b>
<% }else if(num>guess) { %>
<h3>You Guessed Lower...Try Bigger Number</h3>
<% }else{ %>
<h3>You Guessed Higher...Try Smaller Number</h3>
<% }
}
if (flag) { c++; %>
<h3>I Guessed a Number between 1 to 100. Try To Guess..</h3>
<form name="guess" action="try.jsp?c=<%= c%>" method="post">
<input type="text" value="<%=num %>" name="val" hidden>
Make Your Guess : <input type="text" name="guess" size=10 maxlength=3>
<input type="submit" value="GO">
</form>
<% } %>
</body>
</html>

You could pass the user number back as a query parameter.
I'm guessing you are not too familiar with the MVC pattern or Spring, but there are plenty of resources available to get you quickly up and running. I'll try to make a strip down demo later, if I remember.

Related

How to pass java string variable to the javascript function by jsp expression tag?

I want to passing a java String variable to the javascript function parameter using jsp expression tag.Below is my jsp page.
First.jsp
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script>
function stringGenerate(str){
var x = document.getElementsByTagName("input");
x[0].value = str;
}
function numberGenerate(num){
var x = document.getElementsByTagName("input");
x[1].value = num;
}
</script>
</head>
<body>
<%
String num ="1234567890";
String str = "abcdefghij";
%>
<input type="text" name="string" readonly="readonly"/>
<input type="text" name="number" readonly="readonly"/><br/><br/>
<input type="button" value="String Generate" onclick= "stringGenerate(<%=str %>)" />
<input type="button" value="Number Generate" onclick= "numberGenerate(<%=num %>)" />
</body>
</html>
When I click on the button with value "Number Generate",then the num variable value(1234567890) will display on the textbox(name="number") but when I click on the button with value "String Generate",then there is nothing display on the corresponding text box(name="string").Here both num and str are string type varible but why only num variable value is displayed on textbox and why not str variable value is displayed?
Try using single quote ' when using string in HTML:
onclick= "stringGenerate('<%=str %>')"
^ ^
Full Code:
<input type="button" value="String Generate" onclick= "stringGenerate('<%=str %>')" />
The reason is that when the page is rendered by the browser, it puts the str and num values directly in the code, so it looks like:
<input type="button" value="String Generate" onclick="stringGenerate(abcdefghij)"/>
The browser basically thinks you're trying to reference a Javascript variable called 'abcdefghij'.
You should add the ' chars before and after your string text to let javascript know it should use the value of that text and not search for a variable with that name.
The declaration of str should look like this to make it work:
String str = "\'abcdefghij\'";
Please note, you can't use \" to escape as this would break your code.

Embedding JavaScript code in JSP won't call the JS function

Given the following code :
<%# page language="java"
contentType="text/html; charset=windows-1256"
pageEncoding="windows-1256"
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title>Bank application</title>
<link rel="stylesheet"
href="./css/styles.css"
type="text/css"/>
</head>
<body>
<table class="title">
<tr><th>Web Bank application</th></tr>
</table>
<br/>
<script>
function verifyEmptyString()
{
var username = document.forms["loginForm"]["username"].value;
var password = document.forms["loginForm"]["password"].value;
return !(username == null || username == "" || password == null || password == "");
}
</script>
<fieldset>
<legend>Login Page - please enter your Username and Password</legend>
<form id="loginForm" action="loginPage" onsubmit="verifyEmptyString()" >
<p style="font-size:15px"> <span style="color:red;font-weight:bold;">*</span> Username: <input type="text" name="username"><br> </p>
<p style="font-size:15px"><span style="color:red;font-weight:bold;">*</span> Password : <input type="password" name="password"><br> </p>
<input type="submit" value="Login">
</form>
</fieldset>
<br/>
<br/>
<br/>
<br/>
<br/><br/><br/><br/><br/><br/>
</body></html>
I'm trying to call the JS function verifyEmptyString() , but the JSP doesn't call the function.
Any idea what's wrong with the code ?
The function is being called (I added an alert to verify). But you want to return the value of the function in the onclick event:
<form id="loginForm" action="loginPage" onsubmit="return verifyEmptyString(this)" >
Try something like this : http://jsfiddle.net/daguru/RBYnc/1/
var myForm = document.getElementById('loginForm');
myForm.addEventListener("submit", function(ev) {
ev.preventDefault(); // to stop the form from submitting
var username = document.forms["loginForm"]["username"].value;
var password = document.forms["loginForm"]["password"].value;
if(!(username == null || username == "" || password == null || password == "")){
this.submit(); // If all the validations succeeded
alert("submiting")
}
});
Here is the solution :
<form onsubmit="return verifyEmptyString(this)" id="loginForm" action="loginPage" >
For anyone who might encounter this problem in the future , you need to change the onsubmit ...
From this :
onsubmit="verifyEmptyString()"
To this :
onsubmit="return verifyEmptyString(this)"
I do not quite understand why we need to pass thisas a parameter to the function, because it is not accepted in the actual function definition function verifyEmptyString() . You are directly referring the form elements inside the function.
On the otherhand, if your code is similar to the below scenario,
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm(obj) {
var x = obj["firstname"].value;
alert(x);
if (x == null || x == "") {
alert("First name must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="action.jsp"
onsubmit="return validateForm(this)" method="post">
First name: <input type="text" name="firstname"> <input
type="submit" value="Submit">
</form>
</body>
</html>
In this scenario, we are making use of the passed parameter this.
It refers to the current context, In our case, it is the form whose name is myForm
But in your original scenario, you are directly referring the form inside the javascript function by calling document.forms["loginForm"]["username"].value.

How to include HTML in JSP?

I've searched for this question, there are some answers, but not exactly as my question. So, here is my jsp code:
<body>
<%
if (manager.isValid(request.getParameter("username"),request.getParameter("password"))){
out.print("<h1> Welcome ");
out.print(request.getParameter("username") + "</h1>");
} else {
out.print("<h1> Please Try Again </h1> <br />");
out.print("Either your username or password is incorrect. Please Try again <br /> <br />");
}
%>
<%# include file="LoginForm.html" %>
but instead of this, I want to include "loginForm.html" only in "else" block.
How can I do it?
Of course this doesn't work, but you'll guess what I want:
<%
if (manager.isValid(request.getParameter("username"),request.getParameter("password"))){
out.print("<h1> Welcome ");
out.print(request.getParameter("username") + "</h1>");
} else {
out.print("<h1> Please Try Again </h1> <br />");
out.print("Either your username or password is incorrect. Please Try again <br /> <br />");
include file="LoginForm.html" ;
}
%>
I would like to show you a way, try like below. You can try with else instead with if.
<body>
<%
int x = 10;
if(x>10) {
%>
<%#include file="some.html" %>
<%
}
%>
</body>
You could also include reusable html in a jsp file function and call it for printing where needed. e.g.
config.jsp contains
<%!
public void printMenu()
{
%>
HTML HERE
<%!
}
%>
home.jsp contains
<%#include file="config.jsp"%>
<!DOCTYPE html>
<html>
<body>
<% printMenu(); %>
<div id="PeopleTableContainer" style="width: 800px;"></div>

JSP - Get score from a jsp quiz application

Hi I'm creating a quiz application in jsp and am using different jsp pages for every question. I'd like to keep a score after each question is answered. My problem is that I'm picking random answers from a database, within which lies the correct answer too. Since I can't guess which letter the correct answer will appear on, could you suggest what I should do? I am posting the first and second question jsp's to give you an idea of how I'm doing it:
q1.jsp
<%#page import="java.util.Random"%>
<%#page import="java.util.ArrayList"%>
<%#page import="org.me.jsp.beans.WordBean"%>
<%#page import="java.util.List"%>
<!--This JSP acts as the first question in a multiple choice quiz, with the user
asked to submit their answer to the question-->
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<jsp:useBean id = "wordData" scope = "request"
class = "org.me.jsp.beans.WordDataBean" />
<html>
<head>
<title>Big Java Quiz, question 1</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<%if (request.getParameter("choice").equals("N")) {
out.print("<meta http-equiv='refresh' content='0;url=options.jsp'/>");
}
//Redirects user back to index if they did not want to take quiz%>
<form action="q2.jsp" method="POST">
<%
List<WordBean> wordList = wordData.getWordList();
List<String> answersList = new ArrayList<String>();
Random random = new Random();
Random forAnswers = new Random();
WordBean goodOne = wordList.get(random.nextInt(wordList.size()));
//take it out from the list
wordList.remove(goodOne);
//add it to the answers list
answersList.add(goodOne.getGermanName());
WordBean fakeOne = wordList.get(random.nextInt(wordList.size()));
//take it out from the list
wordList.remove(fakeOne);
//add it to the answers list
answersList.add(fakeOne.getGermanName());
WordBean fakeTwo = wordList.get(random.nextInt(wordList.size()));
//take it out from the list
wordList.remove(fakeTwo);
//add it to the answers list
answersList.add(fakeTwo.getGermanName());
%>What is the English word for the German word <%=goodOne.getEnglishName()%>?<br>
<%
char letter = 'A';
for (String answer : answersList) {
%>
<input type="radio" name="q1Answer" value=""/><label for="<%=letter%>"><%=letter%>)<%=answersList.get(forAnswers.nextInt(3))%> />
<% //point to the next letter
letter++;
}
%>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
q2.jsp
<%--
Document : q2
Created on : 06-May-2012, 18:54:32
Author : encore
--%>
<!--This JSP acts as the second question in a multiple choice quiz, with the user
asked to submit their answer to the question-->
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Big Java Quiz, question 2</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<%int score = 0;
if(request.getParameter("q1Answer").equals("C"))
score++; //Increments score if answer submitted was correct%>
<form action="q3.jsp" method="POST">
Your current score is: <%out.print(score);%>/20
<input type="hidden" name="q2Score" value="<%out.print(score);%>"/>
<!--Hidden button allows score to be accessed by next JSP-->
<b>Question 2.</b> When an exception is generated it is said to have been _________?<br/><br/>
<input type="radio" name="q2Answer" value="A"/><label for="A">A) Built</label><br/>
<input type="radio" name="q2Answer" value="B"/><label for="B">B) Thrown</label><br/>
<input type="radio" name="q2Answer" value="C"/><label for="C">C) Caught</label><br/>
<input type="radio" name="q2Answer" value="D"/><label for="D">D) Detected</label><br/><br/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
Note: the form of the second question will obviously be changed to something else, currently I'm concentrating on getting the score .
In the page for Q1, where you should know the correct answer, put it in the session and then retrieve it in the next page.

JSP User Hit Counter

I am trying to count how many times each user enters the website, but my problem is that even though I change the user name, the hit count doesn't restart. Also, once I reload the webpage, the the name of the user becomes "null".
<HTML>
<BODY>
<FORM METHOD=POST ACTION="SaveName.jsp">
Who are You ? <INPUT TYPE=TEXT NAME=username SIZE=20>
<P><INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>
<%# page import="java.io.*,java.util.*" %>
<html>
<head>
<title>Applcation object in JSP</title>
</head>
<body>
<%
String name = request.getParameter( "username" );
session.setAttribute( "theName", name );
Integer hitsCount =
(Integer)application.getAttribute("hitCounter");
if( hitsCount ==null || hitsCount == 0){
/* First visit */
out.println("Welcome to my website! ");
hitsCount = 1;
}else{
/* return visit */
out.println("Welcome back to my website!");
hitsCount += 1;
}
application.setAttribute("hitCounter", hitsCount);
%>
<%= session.getAttribute( "theName" ) %>
<br>Total number of visits: <%= hitsCount%></br>
</body>
</html>
In Your JSP
<%!
Map<String,Integer> userCountMap = new HashMap<String,Integer>();
Integer hitsCount=0;
String key;
%>
<%
String name = request.getParameter( "username" );
if(name!=null && !"".equals(name)){
key=name.toLowerCase();
if(userCountMap.get(key)!=null){
/* return visit */
out.println("<h3>"+name+"</h3> Welcome back to my website!");
hitsCount = userCountMap.get(key);
hitsCount+=1;
}else{
out.println("<h3>"+name+"</h3> Welcome to my website!");
hitsCount=1;
}
userCountMap.put(key, hitsCount);
}
%>
Are you storing the hit counts per user or you are storing just the hit counts?
In the former case, you can use a map that will check whether there is an entry for a specific user in the map. If entry is found, increase the counter by 1, if entry is not found, then create a new entry and set corresponding counter to 1.
In the later case, all you need to do is increase the counter every time the website is hit.

Categories