【问题标题】:Is there a way to split JTextField with substrings into a double?有没有办法将带有子字符串的 JTextField 拆分成双精度?
【发布时间】:2019-04-27 08:40:52
【问题描述】:

有没有一种方法可以使用子字符串拆分 JTextField 并返回它有一个双精度值。问题是我会收到用户的输入,即 JTextField 中的 3+x+5*7+y 或 5*y-x/4 ,这将是一个字符串。但是为了在我的计算中使用它,我相信它必须被拆分或解析成一个双变量。

我相信您可以获取文本的索引,并检查每次出现 -、+、*、/、x 或 y,并将子字符串设置在一起,但我不知道如何做到这一点。

它将是一个名为 double i 的变量,并在以下上下文中使用:

public void solve(double y, double h, int j, double i){      
xArray = new double[j];
yArray = new double[j];
for(int dex = 0; dex < j; dex++){
    F1 = h*f(x,y,i);
    F2 = h*f(x+h/2,y+F1/2,i);
    F3 = h*f(x+h/2,y+F2/2,i);
    F4 = h*f(x+h,y+F3,i);

    y = y + 1.0/6.0*(F1+2*F2+2*F3+F4);

    xArray[dex] = x;
    yArray[dex] = y;

    x = x + h;
   }   
 } 
private double f(double x, double y, double i){
 return i; 
} 

【问题讨论】:

标签: java swing parsing double jtextfield


【解决方案1】:

我相信您可以获取文本的索引,并检查每次出现 -、+、*、/、x 或 y 并将子字符串设置在一起,但我不知道如何做到这一点。

这可以通过KeyListener 接口完成,它提供了 3 种方法可以帮助您keyPressedkeyReleasedkeyTyped 它们每个都有自己的功能(虽然他们的名字会检查出来但他们的时间执行次数变化很大。)

这是一个例子

public class MyListener implements KeyListener {

        @Override
        public void keyTyped(KeyEvent e) {
            //empty implemntation , we are not using it 
        }

        @Override
        public void keyPressed(KeyEvent e) {
            //here we are implementing what we want for the app
            //using the KeyEvent method getKeyChar() to get the key that activated the event.
            char c = e.getKeyChar();
            //let's check it out !
            System.out.println(c);
            //now we got it we can do what we want 
            if (c == '+'
                    || c == '-'
                    || c == '*'
                    || c == '/') {
                // the rest is your's to handle as your app needs
            }
        }

        @Override
        public void keyReleased(KeyEvent e) {
            //empty implemntation , we are not using it 
        }

    }

所以要获取用户点击的键,我们从 KeyEvent 对象中获取它。

当来到组件部分时,我们像这样添加它

JTextComponent jtc = //create it whether it's text field , area , etc...
MyListener ml = new MyListener();
jtc.addKeyListener(ml);

其余的取决于您将如何使用文本 String 并记住这个答案是如何知道用户刚刚输入的内容(逐个字符),但作为一种方法,它非常糟糕!想象一下用户决定删除一个数字或更改插入符号的位置,您将如何处理? 所以正如我们的朋友@phflack 所说,我会推荐使用RegexString.split 像这样:-

String toSplit = "5-5*5+5";
        String regex = "(?=[-+*/()])";
        String[] splited = toSplit.split(regex);
        for (String s : splited) {
            System.out.print(s + ",");
        }

以及这个的输出

5,-5,*5,+5,

但这几乎不是Regex 我只是向您展示了有关Regex read thisKeyListener 的更多信息的示例,您可以阅读它here 并希望这能解决您的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-24
    • 2015-07-20
    • 2023-02-24
    • 1970-01-01
    • 2012-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多