jsp和javabean制作一个简单的计算器
1、 当输入第一个操作数为3,第二个操作数为4,运算符为+时,如图1所示。
图1 运算结果【1】
2、 当输入第一个操作数为a,第二个操作数为1,运算符为任意一个,由于程序中有例外处理,所以打印“有例外发生!”的信息,如图2所示。
图2 运算结果【2】
最后将整个程序压缩打包,上传
[最优解释]
out.println(num1+"+"+num2+"=");
你都没输入结果。
看下这个
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.util.*" %>
<%@ page import="test.Calculate" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<jsp:useBean id="suan" scope="application" class="test.Calculate"></jsp:useBean>
<%
String str1=request.getParameter("num1");
String str2=request.getParameter("num2");
String item = request.getParameter("item");
try{
Double num1=Double.parseDouble(str1.trim());
Double num2=Double.parseDouble(str2.trim());
suan.setNum1(num1);
suan.setNum2(num2);
if(item.equals("+")){
out.println(num1+"+"+num2+"="+(num1+num2));
}
}catch(Exception e){
out.println("有例外发生!");
}
%>
</body>
</html>
package test;
public class Calculate {
private double num1;
private double num2;
private String operator;
public void setNum1 (double num1)
{this.num1=num1;}
public void setNum2 (double num2)
{this.num2=num2;}
public double getNum1()
{return num1;}
public double getNum2()
{return num2;}
public double jia(){
double num3=num1+num2;
return num3;
}
public double jian(){
double num3=num1-num2;
return num3;
}
public double cheng(){
double num3=num1*num2;
return num3;
}
public double chu(){
double num3=num1/num2;
return num3;
}
}
<%@ page contentType="text/html;charset=GB2312" %>
<%@ page import="java.util.*" %>
<%@ page import="test.Calculate" %>
<center>
<FORM action="Calculate.jsp" Method="post" >
<p>第一个操作数: <Input type=text name="num1">
<p>运算符: <Select name="item" value="没选择">
<Option value="+">+</Option>
<Option value="-">-</Option>
<Option value="*">×</Option>
<Option value="/">÷</Option>
</Select>
<p>第二个操作数: <Input type=text name="num2">
<Input type=submit value="提交">
</FORM>
<jsp:useBean id="suan" scope="application" class="test.Calculate"></jsp:useBean><%
String str1=request.getParameter("num1");
String str2=request.getParameter("num2");
try{
Double num1=Double.parseDouble(str1.trim());
Double num2=Double.parseDouble(str2.trim());
suan.setNum1(num1);
suan.setNum2(num2);
if(item.equals("+")){
out.println(num1+"+"+num2+"=");}
}catch(Exception e){
out.println("有例外发生!");}
%>
</center>