jsp实现简易计算器

一、案例演示

输入两个数实现加减乘除,结果输出到页面上
jsp实现简易计算器_第1张图片

二、实现步骤

1、addall.jsp

简易的jsp代码,有两个输入框,四个提交按钮

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="alladdtwo.jsp" method="post">
    number1:<input name="number1" type="text"><br>
    number2:<input name="number2" type="text"><br>
    <input name="in" type="submit" value="+">
    <input name="in" type="submit" value="-">
    <input name="in" type="submit" value="*">
    <input name="in" type="submit" value="/">
</form>
</body>
</html>

1、addalltwo.jsp

嵌套在jsp中的java代码,接收两个输入值,通过判断运算符进行相应运算,注意除数不为零的情况通过<%=%>输出嵌套在jsp中的java值

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="" method="post">
    number1:<input name="number1" type="text"><br>
    number2:<input name="number2" type="text"><br>
    <input name="in" type="submit" value="+">
    <input name="in" type="submit" value="-">
    <input name="in" type="submit" value="*">
    <input name="in" type="submit" value="/">
</form>

<%
    String number1=request.getParameter("number1");
    int n1= Integer.parseInt(number1);
    String number2=request.getParameter("number2");
    int n2=Integer.parseInt(number2);
    String in=request.getParameter("in");
    String result="";
    if("+".equals(in)){
        result= String.valueOf(n1+n2);
    }
    if("-".equals(in)){
        result= String.valueOf(n1-n2);
    }
    if("*".equals(in)){
        result= String.valueOf(n1*n2);
    }
    if("/".equals(in)){
        if("0".equals(number2)){
            result="除数不能为零";
        }else {
            result= String.valueOf(n1/n2);
        }
    }
%>
<p style="color: #0066FF">结果:<%=n1%> <%=in%> <%=n2%> = <%=result%></p>
</body>
</html>

你可能感兴趣的:(java,web,前端,后端,java,javascript,servlet)