How to use jsp to implement a simple calculator (3)
This jsp page is mainly used to implementThe ability to submit and accept data on the same page.
This small program has many shortcomings. I hope you can criticize and correct it more.
<% @ Page language = "java" contentType = "text/html;" pageEncoding = "gbk" %>
My simple calculate<Script type = "text/javascript"> // input judgment, which must be in the numeric format: function check_num () {var re =/^ [0-9,] * $ /; if ((! (New RegExp ("\ S +"). test (document. getElementById ("number1"). value ))&&(! (New RegExp ("\ S +"). test (document. getElementById ("number2"). value) {alert ("Please input one or two! "); Document. getElementById (" number1 "). focus (); return false;} else if (! (New RegExp ("\ S +"). test (document. getElementById ("number1"). value) {alert ("Please input one! "); Document. getElementById (" number1 "). focus (); return false;} else if (! (New RegExp ("\ S +"). test (document. getElementById ("number2"). value) {alert ("Please input two! "); Document. getElementById (" number2 "). focus (); return false;} if ((! Re. test (document. getElementById ("number1"). value ))&&(! Re. test (document. getElementById ("number2"). value) {alert ("number 1 and number 2 are not numbers. Please enter a number! "); Document. getElementById (" number1 "). focus (); return false;} else if (! Re. test (document. getElementById ("number1"). value) {alert ("Number 1 is not a number. Please enter a number! "); Document. getElementById (" number1 "). focus (); return false;} else if (! Re. test (document. getElementById ("number2"). value) {alert ("number 2 is not a number. Please enter a number! "); Document. getElementById (" number2 "). focus (); return false;} document. form1.submit (); return true ;}</script><% // Obtain the number of inputs in the input box. String numString1 = request. getParameter ("number1"); String flagString = request. getParameter ("flag"); String numString2 = request. getParameter ("number2"); int num1 = 0; int num2 = 0; int result = 0; boolean flag = false; // determines whether the input value is null, not empty, calculate if (numString1! = Null & numString2! = Null) {num1 = Integer. parseInt (numString1); num2 = Integer. parseInt (numString2); flag = true; if (flagString. equals ("+") {result = num1 + num2;} else if (flagString. equals ("-") {result = num1-num2;} else if (flagString. equals ("*") {result = num1 * num2;} else {result = num1/num2 ;}%> simple calculator
Calculation result: <% if (flag) out. println (result); flag = false; %>
The implementation result is as follows: