用Javaweb写一个三角形面积的代码
时间: 2024-11-05 10:26:11 浏览: 24
在Java Web环境中编写一个计算三角形面积的简单示例,我们可以创建一个Servlet来进行这个操作。首先,我们需要创建一个HTML表单让用户输入三角形的底和高。然后,Servlet将接收这些值并计算面积。
```java
// 服务器端(Servlet)部分 - TriangleAreaServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class TriangleAreaServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String base = request.getParameter("base");
String height = request.getParameter("height");
if (base.isEmpty() || height.isEmpty()) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Base and height are required.");
return;
}
double baseDouble = Double.parseDouble(base);
double heightDouble = Double.parseDouble(height);
double area = 0.5 * baseDouble * heightDouble;
try (PrintWriter out = response.getWriter()) {
out.println("The area of the triangle is: " + area);
}
}
}
// HTML 表单部分 - index.jsp 或者 web-INF/views/triangle.html
<form action="TriangleAreaServlet" method="post">
<label for="base">Base:</label>
<input type="text" name="base" id="base"><br>
<label for="height">Height:</label>
<input type="text" name="height" id="height"><br>
<input type="submit" value="Calculate Area">
</form>
```
用户访问`/TriangleAreaServlet`提交表单后,服务器会计算并返回结果。注意这只是一个基础示例,实际应用中需要处理更复杂的边界条件和异常情况。
阅读全文