Search code examples
javaarraysapplet

How to create an array by inputting numbered into a textfield, Java applet


My assignment is to input 20 numbers via a text field then out the mean, the median and the total using a while loop. I should be able to figure out the while loop myself, but I can't get the text field to input numbers into an array. Please help, here is my code so far:

 import java.applet.Applet;
import java.awt.Graphics;
import java.awt.*;
import java.awt.event.*;

public class whileloopq extends Applet implements ActionListener
{
    Label label;
    TextField input;
    int[] numArray = new int[20];
    int num;

    public void init ()
    {
        Label label = new Label("Enter numbers");
        TextField input = new TextField(5);
        add(label);
        add(input);
        input.addActionListener(this);
    }

    public void actionPerformed (ActionEvent ev)
    {
        int num = Integer.parseInt(input.getText());
        int index = 0;
        numArray[index] = num;
        index++;
        input.setText("");

    }

    public void paint (Graphics graf)
    {
        graf.drawString("Array" + numArray, 25, 85);
    }
}

Any help would be much appreciated.


Solution

  • In actionPerformed() you are trying to read from class filed input.setText("");

    but in init() you didn't initialized that field but created and added to applet local variable

    TextField input = new TextField(5);
    

    so class field is steal null. Change it to

    input = new TextField(5);