1. 程式人生 > >j2ee-JSP之簡單計算器

j2ee-JSP之簡單計算器

name 輸出 運算符 教程 htm false hide fun 計算器

來源韓順平.j2ee視頻實戰教程jsp第1講(下集)

--------------------------------------------------------------------------------------------------------

簡單計算器,可以控制輸入的數(僅第一個數)不能為空且不能為字符串

myCal.jsp代碼

技術分享
 1 <!--這是計算器的界面 -->
 2 <!-- 可以控制輸入的數不能為空且不能為字符串 -->
 3 <%@ page contentType="Text/html;charset=gb2312" %>
 4
<html> 5 6 <h1>我的計算器</h1> 7 <hr> 8 <head> 9 <!-- 在jsp中添加代碼,防止用戶空提交 --> 10 <script language="javascript"> 11 <!-- 12 //寫一個函數驗證用戶是不是空提交 13 function checkNum(){ 14 //判斷num1,是不是空的 15 if(form1.num1.value ==""){ 16 window.alert("num1不能為空!!!");//
彈出一個對話框 17 return false; 18 19 } 20 //判斷num1是不是一個數 21 if(Math.round(form1.num1.value)!=form1.num1.value){ 22 window.alert("num不是一個數!!!");//彈出一個對話框 23 return false; 24 } 25 26 27 } 28 --> 29 30 </script> 31 </head> 32 33 <body> 34 <form name="form1" action="myResult.jsp"> 35
請輸入第一個數:<input type="text" name="num1"><br> 36 <select name="flag"> 37 38 <option value=+>+</option> 39 <option value=->-</option> 40 <option value=*>*</option> 41 <option value=/>/</option> 42 </select><br> 43 請輸入第二個數:<input type="text" name="num2"><br> 44 <input type="submit" value="計算" onclick="return checkNum()"> 45 46 </form> 47 <hr> 48 </body> 49 </html>
View Code

myResult.jsp代碼

技術分享
 1 <%@ page contentType="Text/html;charset=gb2312" %>
 2 <html>
 3   <body>
 4   <%
 5   //接受到第一個數
 6    String s_num1=request.getParameter("num1");
 7   //接受第二個數
 8    String s_num2=request.getParameter("num2");
 9   //接受運算符號
10    String flag = request.getParameter("flag");
11   int num1=0;
12   int num2=0;
13   int result=0;
14   //java中 String -> int
15   num1=Integer.parseInt(s_num1);
16   num2=Integer.parseInt(s_num2);   
17   //計算
18   if(flag.equals("+")){
19   //
20   result =num1+num2; 
21   }else if(flag.equals("-")){
22     result =num1-num2; 
23   //
24   }else if(flag.equals("*")){
25     result =num1*num2;
26   //
27   }else{
28     result =num1/num2; 
29   //
30   }
31   //輸出結果
32  out.println("結果是:"+result); 
33    %>
34    
35   </body>
36 </html>
View Code

界面效果:

技術分享

技術分享

技術分享

---------------------------------------------------------------------------------------------------------------------------------------------

j2ee-JSP之簡單計算器