有关JSP计算的问题

时间:2010-01-09 10:28:47

标签: java jsp

这段代码的问题在于我的作者受欢迎程度为0%(如果借书数量为14且所选作者借书总数为3,我的意思是零% - 应该是是21.42%)。为什么会这样?

除最后一项外,所有结果都是正确的:

作者0%受欢迎(针对上述数据)

<%
String requestedoprations = request.getParameter("popularity");
if("check".equalsIgnoreCase(requestedoprations)){
    int num=LimsHandler.getInstance().popularitycheck(
        request.getParameter("selectedauthor"));
    if(num!=0){
        Limsdetails[] list = LimsHandler.getInstance().libsdetails();
        String totbks=list[0].getTot_books();
        String totbrwdbk=list[0].getTot_borrowed_bks();
        int totbksint=Integer.parseInt(totbks);
        int totbrwdbksint=Integer.parseInt(totbrwdbk);
        float per=(num/totbrwdbksint)*100;          
%>
<font color="brown">
    <b>Total No of Books Available in Library is : <%=totbksint %><br></br>
    Out of which <%=totbrwdbksint %> are borrowed.<br></br>
    <b>No of readers reading Author 
        <%=request.getParameter("selectedauthor") %>'s book. : 
        <%=num %></b><br></br>
    <b> Author <%=request.getParameter("selectedauthor") %> is <%=per %> % 
        popular!</b><br></br>
</font>

<%}else{ %>
    <h4 align="center">
        <font color="red">
            <img border="0" src="images/close.PNG" ><br></br>
            Oops! some error occurred!
        </font>
    </h4>
<%
}
out.flush();
%>

<%} %>

3 个答案:

答案 0 :(得分:5)

这不是一个JSP问题 - 它是Java处理整数运算的方式。相关的行是:

int num = LimsHandler.getInstance().popularitycheck(...);
int totbrwdbksint = Integer.parseInt(totbrwdbk);
float per = (num / totbrwdbksint) * 100;

你正在执行“int / int”除法然后再乘以100.这将使用整数运算执行除法 - 因此结果将为0.将0乘以100仍然得到0

解决此问题的最简单方法是将其中一个值设为floatdouble。例如:

int num = LimsHandler.getInstance().popularitycheck(...);    
float totbrwdbksint = Integer.parseInt(totbrwdbk);
float per = (num / totbrwdbksint) * 100;

或者,您可以在表达式中进行转换:

int num = LimsHandler.getInstance().popularitycheck(...);
int totbrwdbksint = Integer.parseInt(totbrwdbk);
float per = (num / (float) totbrwdbksint) * 100;

此时,将使用浮点运算执行除法,您将得到您期望的答案。

答案 1 :(得分:1)

这不是原始问题的解决方案,但我建议学习两件新事物:

  1. JS​​TL
  2. CSS
  3. 你的JSP中既没有嵌入scriptlet也没有样式。你会感谢自己有朝一日努力,因为维护和重新设置你的页面会更容易。

答案 2 :(得分:0)

计算方式

float per=(num/totbrwdbksint)*100  
执行

(num/totbrwdbksint)的结果四舍五入为零。

尝试

float per=((float)num/(float)totbrwdbksint)*100  

获得更好的结果。