0

I have a form , i want to input numbers one at a time.

I create an object and pass the getParameter() values to it,

   <form action="index.jsp" name="form" method="GET">
    <input type="text" value="" name="input" />
    <input type="hidden" name="hiddenCounter"  value="" />  
    <%
    String input = request.getParameter("input");
    String hiddenCounter = request.getParameter("hiddenCounter");               
    control.MainProgram main = new control.MainProgram(input, hiddenCounter);
    %>           

    <input type="submit" value="Submit Numbers" />
    <% out.println(main.getResult()); %>
    </form>  

The constructor in a java class parses the values to int and sets the variables

public MainProgram(String input, String hiddenCounter) {    

    try {         
       number = Integer.parseInt(input);           
       counter = Integer.parseInt(hiddenCounter);           
    } catch (NumberFormatException e) {
    }        
}


public int getResult() {
    return number;
}

how can i sum up the numbers each time a number is submitted?

The problem is every time the constructor is called it sets the variable to the numbers submitted.

something like

number+=number; 

dosent work ( cause its resetting the variable )

ive searched & searched can someone help ?

4

2 回答 2

0

If you're not worried about multi-threaded access, you can simply declare number static.

The variable will be bound to the control.MainProgram class rather than its instance.

You then...

try {         
       number += Integer.parseInt(input); 

... then declare getResult static as well...

... then invoke it by <% out.println(control.MainProgram.getResult()); %>

Note that this doesn't give you the average, as your title implies - it gives you the sum.

But it's simple enough to implement an average in the body of your static int getResult method.

于 2014-10-10T16:25:38.713 回答
0

您必须将总和的运行总计传递给会话变量。您可以通过像这样获取会话来做到这一点 HttpSession session = request.getSession(); session.setAttribute("UserName", username); 然后您可以使用 getAttribute() 函数获取属性。这应该适用于并发用户。如果您需要更多帮助

于 2014-10-10T16:29:22.503 回答