Request.getParameter到int?

时间:2015-05-08 01:10:06

标签: java jsp calculator

好的,所以我有一个大学项目在JSP中制作一个非常简单的计算器。事情是我得到一个错误的结果= a(x)b行,因为二进制操作的操作数不好" x"其中X是我想要做的功能的象征。 我不确定出了什么问题... a + b说我不能将字符串转换为int但是我不能做一个Integer a = request.getParameter ......等等 非常感谢任何帮助或提示...

这是我的index.html

 <html>
        <head>
            <title>Calculator</title>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
        </head>
        <body>
            <form name="Parameters" method="post" action="calc.jsp">
                <i>You know you have a built-in calculator in your OS, right?</i><br><br>

                Number 1: <input type="text" name="param1"><p>
                Number 2: <input type="text" name="param2"><p>
                Function: <input type="text" name="function" maxlength="1"><br><br>
                 <input type="submit" value="Submit">
            </form>
        </body>
    </html>

这是我的calc.jsp

<%-- 
    Document   : calc
    Created on : May 8, 2015, 2:45:00 AM
    Author     : Doom
--%>
>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%    
int result;
String resp;
String a=request.getParameter("param1");
String b=request.getParameter("param2");
String f=request.getParameter("function");

if (f.equals("+"))
    result= a+b;
else if(f.equals("-"))
    result=a-b;
else if(f.equals("*"))
    result=a*b;
else if(f.equals("/"))
    result=a/b;
else
    resp="Invalid Function";
%>r
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Calculator</title>
    </head>
    <body>

    </body>
</html>

1 个答案:

答案 0 :(得分:1)

如果您正在使用计算器,则可能需要将字符串输入转换为double而不是int。在这种情况下,解决方案是:

double d = Double.parseDouble(aString);

如果你希望分割结果在整数分割时正确显示,那么你的result肯定需要是双倍。

您还需要处理用户提交非数字值的异常。