如何将String从JTextField转换为double数组

时间:2013-03-05 19:08:57

标签: java arrays swing double jtextfield

我目前正在尝试从两个JTextField读取值,通过递增1找到值的范围,然后将值写入Double数组。然而,我所采用的方式似乎并不起作用,我无法在Google /互联网上找到解决方案。

到目前为止,这是我的代码:

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 ++;

        }
    }
}
}

提前致谢。 :)

2 个答案:

答案 0 :(得分:2)

您尚未初始化数组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 ++;
}

答案 1 :(得分:0)

你的意思是maxValue1是最小值,maxValue2是该范围内的最大值吗? 如果是这样,试试这个:

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

        int length = (int) value2 + 1 - (int) value1;
        x = new double[length];

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