jsp计算器代码加减乘除
时间: 2023-07-03 18:04:01 浏览: 155
以下是一个简单的 JSP 计算器代码,支持加减乘除:
```
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSP Calculator</title>
</head>
<body>
<form method="post" action="">
<input type="text" name="num1" placeholder="Number 1" required /><br />
<input type="text" name="num2" placeholder="Number 2" required /><br />
<select name="operator">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select><br />
<input type="submit" value="Calculate" />
</form>
<%-- Handle form submission --%>
<%
if (request.getMethod().equalsIgnoreCase("POST")) {
int num1 = Integer.parseInt(request.getParameter("num1"));
int num2 = Integer.parseInt(request.getParameter("num2"));
String operator = request.getParameter("operator");
int result = 0;
switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
result = num1 / num2;
break;
default:
out.println("Invalid operator");
break;
}
out.println("<br />Result: " + result);
}
%>
</body>
</html>
```
通过表单提交,获取用户输入的两个数和运算符,然后使用 switch 语句计算结果并输出。注意,这个代码只是一个简单的例子,没有进行输入校验和异常处理,实际使用中需要做更多的优化和安全性处理。
阅读全文