Search code examples
javaarraysswingdoublejtextfield

How to convert a String from a JTextField to a double array


I am currently attempting to read in values from two JTextFields, find the range of the values by incrementing by 1 and then writing the values to a Double array. However the way I've done doesn't seem to work and I can't find a solution on Google/ the Internet.

Here is my code so far:

package textfieldtodouble;

import java.awt.*;
import java.util.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Line2D;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyVetoException;
import javax.swing.*;

public class TextFieldToDouble {

JFrame frame = new JFrame();
JPanel panel = new JPanel();
static JTextField maxValue1 = new JTextField(20);
static JTextField maxValue2 = new JTextField(20);
JButton btn1 = new JButton("To Double Array");
double x[];
double value1;
double value2;

void buildTheGUI() {
    panel.add(maxValue1, BorderLayout.NORTH);
    panel.add(btn1, BorderLayout.SOUTH);
    panel.add(maxValue2, BorderLayout.SOUTH);
    btn1.addActionListener(new toDouble());
    frame.add(panel);
    frame.setSize(300, 300);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

TextFieldToDouble() {
    buildTheGUI();
}

public static void main(String[] args) {
    new TextFieldToDouble();
}

class toDouble implements ActionListener {

    public void actionPerformed(ActionEvent event) {
        value1 = Double.parseDouble(maxValue1.getText());
        value2 = Double.parseDouble(maxValue2.getText());

        for (int i = 0; i < value1; i++) {
            System.out.println(i);
            x[i] = value2 + i;
            value2 ++;

        }
    }
}
}

Thanks in advance. :)


Solution

  • You haven't initialized the array x:

    value1 = Double.parseDouble(maxValue1.getText());
    value2 = Double.parseDouble(maxValue2.getText());
    
    int length = (int) value1;
    x = new double[length];
    
    for(int i = 0; i < length; i++)
    {
        System.out.println(i);
        x[i] = value2 + i;
        value2 ++;
    }