A Method to Implement a Simple Calculator Based on JSP

  • 2021-06-29 11:45:05
  • OfStack

An example of how to implement a simple calculator based on JSP is given.Share it for your reference.The implementation is as follows:

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>  
<% 
String path = request.getContextPath(); 
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 
%> 
<html> 
  <head> 
  <!-- User Submit Authentication --> 
  <script type="text/javascript" language="javascript"> 
  <!--  
  function checkNum(){ 
    if(form1.num1.value==""){ 
    window.alert("num1 Value cannot be empty !!Ha-ha "); 
    return false; 
    } 
    // judge num1 Right? 1 Number  
    if(Math.round(form1.num1.value)!=(form1.num1.value)){ 
    window.alert("num1 No 1 Integers ") 
    return false; 
    } 
    if(form1.num2.value==""){ 
    window.alert("num2 Value cannot be empty !!Ha-ha "); 
    return false; 
    } 
    // judge num2 Right? 1 Number  
    if(Math.round(form1.num2.value)!=(form1.num2.value)){ 
    window.alert("num2 No 1 Integers ") 
    return false; 
     
  } 
  } 
  --> 
  </script> 
  </head> 
  <h1> My Calculator </h1> 
  <hr> 
  <body> 
    <form  name ="form1" action="result.jsp" method ="post"> 
    <input type="text" name ="num1" ></input><br> 
    
    <select name="flag"> 
    <option value=+>+</option> 
    <option value=->-</option> 
    <option value=*>*</option>  
    <option value=/>/</option> 
    </select><br> 
     <input type="text" name="num2"/></input><br> 
    <input type="submit" value=" Submit " onclick="return checkNum();"></input> 
    </form> 
    <hr> 
  </body> 
</html>

result.jsp is used to display results

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>  
<% 
String path = request.getContextPath(); 
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 
%> 
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
  <head> 
  </head> 
   
  <body> 
  <% 
    String num1=request.getParameter("num1"); 
    String num2 = request.getParameter("num2"); 
   String flag = request.getParameter("flag"); 
   int s_num1=Integer.parseInt(num1); 
   int s_num2=Integer.parseInt(num2); 
   int result=0; 
  
  if(flag.equals("+")){ 
  // plus  
  result=s_num1+s_num2; 
  }else if(flag.equals("-")){ 
  // reduce  
  result=s_num1-s_num2; 
  }else if(flag.equals("/")){ 
  result=s_num1/s_num2; 
  // except  
  }else{ 
  // ride  
  result=s_num1*s_num2; 
  } 
  out.println(" The result is: "+result); 
   %> 
  </body> 
</html>

I hope that the description in this paper will be helpful to everyone's jsp program design.


Related articles: