猜字游戏!由系统产生一个随机数,存入session中。提供8次机会猜测随机数的值,用户每次猜测数值以及与随机数比较的结果显示在输入框之上,如果猜出随机数,显示“恭喜你猜对了”,当8次机会用完还没有猜对…
输出效果:
代码如下:
<%@ page import="java.util.Random" %><%--
Created by IntelliJ IDEA.
User: 17513
Date: 2021/11/3
Time: 16:29
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>猜数游戏A</title>
<style type="text/css">
div{
height: 210px;
width: 300px;
border: 1px solid #1159a2
}
</style>
</head>
<body>
<%
if(session.getAttribute("num1")==null) {
Random r = new Random();
int n = r.nextInt(100);
session.setAttribute("num1", n);
int sum = 8;
session.setAttribute("sum", sum);
}
%>
<div color="red">
<%
request.setCharacterEncoding("UTF-8");
int num1= (int) session.getAttribute("num1");
String content =(String) application.getAttribute("Topic");
int sum=(int) session.getAttribute("sum");
if(content==null||content=="")
{
application.setAttribute("Topic","猜字游戏:<br>");
content =(String) application.getAttribute("Topic");
}
String contentText="";
// int num2= Integer.parseInt(request.getParameter("Num2"));
String num=request.getParameter("Num2");
if(num!=null) {
int num2 = Integer.parseInt(num);
if (num1 == num2 && sum != 0) {
contentText = "你输入的值是:" + num2 + "恭喜你猜对了!";
} else if (num1 > num2 && sum != 0) {
contentText = "你输入的值是:" + num2 + "比猜测值小了";
sum--;
session.setAttribute("sum", sum);
} else if (num1 < num2 && sum != 0) {
contentText = "你输入的值是:" + num2 + "比猜测值大了";
sum--;
session.setAttribute("sum", sum);
}
if (sum == 0) {
contentText = "猜测值是:" + num1 + "你失败了!";
}
if (contentText != null && contentText != "") {
content = content + contentText + "<br>";
application.setAttribute("Topic", content);
}
}
out.print(content);
%>
</div>
<hr>
<form method="post">
你猜的数:<input type="text" name="Num2">
<input type="submit" value="发送">
</form>
</body>
</html>