Search code examples
javaswingjtextfield

multiply user input through JTextField with an array of double values


I'm very new to Java (and programming in general). I'm working on a program that should accept a double value from user through a JTextField and multiply it with quite a few double values in an array, and display the result in a JTextArea. A kind of calculator you could say.

Right now, I only see the result of the input multiplied with the last value in the array(0.50) and im sure there's something with my loop, array or something missing, I just cant figure out what.

double[] percRM = {0.65, 0.75, 0.85, 0.70, 0.80, 0.90, 0.30, 0.40, 0.50};                
double dDouble;
double pFinal;

if(ae.getSource() == pressbutton){
       pDouble = Double.parseDouble(presstext.getText());
        for (int j=0;j<percRM.length;j++){
            pFinal = percRM[j] * pDouble;
        }
            resulttext.setText("The Sum is:" + "\n" + pFinal+ "\t");
      }

I also have a JFrame with quite a few buttons. Please tell me if you want me to show my entire code.

And while im here, I wonder how I can add some text next to each value printed, lets say user input is 100, the result will be(example):

The sum is:

Week1:
Set1 = 65
Set2 = 75
Set3 = 85
etc.

appreciate any help, thanks


Solution

  • Your problem is that you're calling setText(...) on the JTextArea and doing so after the loop is over. setText(..) will erase everything that the JTextArea is currently showing and replace it with your new text -- now what you want. The append(...) method just adds new text tot he bottom.

    Instead call append(...) and do so inside of the loop.

    for (int i = 0; i < someLength; i++) {
      double value = doSomeCalculation():
      myTextField.append("result: " + value + "\n");
    }