javaBean和jsp实现复数的4则运算(不使用脚本let)
时间: 2024-02-06 13:02:37 浏览: 143
实现复数的四则运算
首先,我们需要定义一个JavaBean来表示复数,包含实部和虚部两个属性:
```java
public class Complex {
private double real; // 实部
private double imag; // 虚部
public Complex(double real, double imag) {
this.real = real;
this.imag = imag;
}
public double getReal() {
return real;
}
public void setReal(double real) {
this.real = real;
}
public double getImag() {
return imag;
}
public void setImag(double imag) {
this.imag = imag;
}
// 复数加法
public Complex add(Complex other) {
return new Complex(this.real + other.real, this.imag + other.imag);
}
// 复数减法
public Complex subtract(Complex other) {
return new Complex(this.real - other.real, this.imag - other.imag);
}
// 复数乘法
public Complex multiply(Complex other) {
double real = this.real * other.real - this.imag * other.imag;
double imag = this.real * other.imag + this.imag * other.real;
return new Complex(real, imag);
}
// 复数除法
public Complex divide(Complex other) {
double denominator = other.real * other.real + other.imag * other.imag;
double real = (this.real * other.real + this.imag * other.imag) / denominator;
double imag = (this.imag * other.real - this.real * other.imag) / denominator;
return new Complex(real, imag);
}
}
```
然后,在JSP页面中使用JavaBean进行复数运算:
```jsp
<jsp:useBean id="complex1" class="com.example.Complex" scope="page">
<jsp:setProperty name="complex1" property="real" value="${param.real1}" />
<jsp:setProperty name="complex1" property="imag" value="${param.imag1}" />
</jsp:useBean>
<jsp:useBean id="complex2" class="com.example.Complex" scope="page">
<jsp:setProperty name="complex2" property="real" value="${param.real2}" />
<jsp:setProperty name="complex2" property="imag" value="${param.imag2}" />
</jsp:useBean>
<p>复数加法:${complex1.add(complex2)}</p>
<p>复数减法:${complex1.subtract(complex2)}</p>
<p>复数乘法:${complex1.multiply(complex2)}</p>
<p>复数除法:${complex1.divide(complex2)}</p>
```
在浏览器中访问这个JSP页面,输入两个复数的实部和虚部,就可以得到四则运算的结果。注意,这里不能使用脚本let,而是使用JSP的EL表达式来调用JavaBean的方法进行运算。
阅读全文