有没有办法可以使用子字符串拆分JTextField并返回它有一个double。问题是我将收到用户的输入,即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;
}
我相信你可以获取文本的索引,并检查每次出现 - ,+,*,/,x或y并将子字符串设置在一起,但我无法弄清楚如何做到这一点。
这可以通过KeyListener
接口完成,它提供了3种方法,可以帮助你keyPressed
,keyReleased
和keyTyped
每个人都有它自己的功能(虽然他们的名字检查出来但他们的执行时间变化很多。)
这是一个例子
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
并记住这个答案是如何知道用户刚刚键入的内容(char by char),但作为一种方法,它非常糟糕!想象用户决定删除一个数字或更改插入位置,你会如何处理?所以我们的朋友@phflack说我建议使用这样的Regex
或String.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 this和KeyListener
的更多信息的样本,你可以读到它here,我希望这解决了你的问题。