jsp计算器代码加减乘除
时间: 2023-07-03 13:08:59 浏览: 123
以下是一个简单的 JSP 计算器代码,实现了加减乘除四则运算:
```
<%@ page language="java" %>
<html>
<head>
<title>JSP Calculator</title>
</head>
<body>
<h2>JSP Calculator</h2>
<form name="calculator" method="post" action="calculator.jsp">
<input type="text" name="num1" size="5" />
<select name="operator">
<option value="add">+</option>
<option value="sub">-</option>
<option value="mul">*</option>
<option value="div">/</option>
</select>
<input type="text" name="num2" size="5" />
<input type="submit" value="Calculate" />
</form>
<%
String operator = request.getParameter("operator");
double num1 = Double.parseDouble(request.getParameter("num1"));
double num2 = Double.parseDouble(request.getParameter("num2"));
double result = 0;
if (operator.equals("add")) {
result = num1 + num2;
} else if (operator.equals("sub")) {
result = num1 - num2;
} else if (operator.equals("mul")) {
result = num1 * num2;
} else if (operator.equals("div")) {
result = num1 / num2;
}
%>
<% if (request.getMethod().equals("POST")) { %>
<p>Result: <%= result %></p>
<% } %>
</body>
</html>
```
该代码首先在页面上显示一个表单,包含两个数字输入框和一个下拉菜单,用于选择运算符。当用户提交表单时,JSP 将获取输入字段的值和所选的运算符,并根据所选的运算符计算结果。最后,将结果显示在页面上。
阅读全文