I believe you can take the index of the text, and check for every time an -, +, *, /, x or y appears and set the substrings together, but I can not figure out how this can be done.
this can be done with KeyListener
interface which it provides 3 methods that can help you keyPressed
, keyReleased
and keyTyped
each one of them has it's own functionality (although them names checks them out but their time of execution varies, a lot.)
here is an example
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
}
}
so to get the key that the users hit we get it from the KeyEvent
object.
when coming to the component part we add it like this
JTextComponent jtc = //create it whether it's text field , area , etc...
MyListener ml = new MyListener();
jtc.addKeyListener(ml);
the rest depends on how you are going to use the text String
and remember this answer's how to know what the users just typed (char by char) but as an approach it's very bad !! imagine that the users decides to remove a digit or to change the caret location ,how would you handle it ??
so as our friend @phflack said I would recommend using Regex
or String.split
something like this:-
String toSplit = "5-5*5+5";
String regex = "(?=[-+*/()])";
String[] splited = toSplit.split(regex);
for (String s : splited) {
System.out.print(s + ",");
}
and the output of this
5,-5,*5,+5,
but this is hardly a Regex
I just showed you a sample for more information about the Regex
read this and for the KeyListener
you can read about it here and I hope this solved your problem.