定义一个javaBean,利用改javaBean能进行加、减、乘、除四则运算。编写jsp页面,利用该javaBean输出四则运算结果
时间: 2024-11-06 18:25:06 浏览: 16
在Java中,我们可以创建一个名为`CalculatorBean`的简单JavaBean,它包含两个属性表示操作数,以及四个方法代表加、减、乘、除的运算。首先,让我们定义这个JavaBean:
```java
public class CalculatorBean {
private double num1;
private double num2;
// 构造函数
public CalculatorBean(double num1, double num2) {
this.num1 = num1;
this.num2 = num2;
}
// 加法方法
public double add() {
return num1 + num2;
}
// 减法方法
public double subtract() {
return num1 - num2;
}
// 乘法方法
public double multiply() {
return num1 * num2;
}
// 除法方法 (需要处理除数为0的情况)
public double divide() throws ArithmeticException {
if (num2 == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
return num1 / num2;
}
}
```
接下来,你可以创建一个JSP页面来接收用户输入,设置`CalculatorBean`的值,并显示计算结果:
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Calculator</title>
</head>
<body>
<h1>Simple Calculator</h1>
<form action="calculate.jsp" method="post">
Number 1: <input type="number" name="num1"><br>
Number 2: <input type="number" name="num2"><br>
Operation: <select name="operation">
<option value="add">Add</option>
<option value="subtract">Subtract</option>
<option value="multiply">Multiply</option>
<option value="divide">Divide</option>
</select><br>
<input type="submit" value="Calculate">
</form>
<%@ include file="calculator.jspx" %>
</body>
</html>
```
然后,在`calculator.jspx`文件中,我们处理表单提交并显示结果:
```jsp
<%-- calculator.jspx --%>
<%
double num1 = Double.parseDouble(request.getParameter("num1"));
double num2 = Double.parseDouble(request.getParameter("num2"));
String operation = request.getParameter("operation");
CalculatorBean calc = new CalculatorBean(num1, num2);
try {
switch (operation) {
case "add":
out.println("Result: " + calc.add());
break;
case "subtract":
out.println("Result: " + calc.subtract());
break;
case "multiply":
out.println("Result: " + calc.multiply());
break;
case "divide":
out.println("Result: " + calc.divide());
break;
}
} catch (ArithmeticException e) {
out.println("Error: " + e.getMessage());
}
%>
```
阅读全文