简体   繁体   中英

How to split a string in Java and then push numbers into one list and operators into another?

I understand splitting a string in Java is something like this:

String[] result = userCalcInput.split("[-+*/]");

But i want to split say the following expressions.

2+2
222*2
2/2+6
120+9/4+22
29*2+9

I want the user to be able to enter anything such as the above or their own choice as a string and then i can split this on the operator and push into the different lists. code so far below:

    List<Integer> numberList = new ArrayList<Integer>();
    List<String> operatorList = new ArrayList<String>();

    Scanner userInputNoOne = new Scanner( System.in );
    System.out.println("Enter your calculation: ");
    userCalcInput = userInputNoOne.next();


    String[] result = userCalcInput.split("[-+*/]");

    if(userCalcInput = int){
        //code here
    }
    else if (userCalcInput = NaN){
        //code here
    }

    System.out.println(result);

I understand this wont work but just wanted to see if right idea and how to properly implement it. thanks

I understand you are quite new to Java.

You could use regular expressions. Regular expressions allow you to find specific patterns in a string, in that case you want to look for numbers and operators, which are defined separately in a 'regex' : \\d for a digit and \\W for a non-word character, such as an arithmetic operator. You should try using the Pattern and Matcher classes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM