Java taking operators from split to assign functions

Okay ... I think I may have changed my mind while trying to simplify this code. I am posting operators like ( *, +, /, -)

in split. I know that I want to name them individually to fulfill my promising task, if (operators.equals.(+)){

return num1 + num2. }

while for *, -, / promising

how can i do it correctly using the math in my previous code:

String function = "[+\\-*/]+"; //this

String[] token = input.split(function);//and this

double num1 = Double.parseDouble(token[0]);

double num2 = Double.parseDouble(token[1]);

double answer;

String operator = input.toCharArray()[token[0].length()]+"";

if (operator.matches(function) && (token[0]+token[1]+operator).length()==input.length()) {

System.out.println("Operation is " + operator+ ", numbers are " + token[0] + " and " + token[1]);
} else {

      System.out.println("Your entry of " + input + " is invalid");
}

      

+3


source to share


2 answers


You do not have.

String.split

returns only those parts String

that were not matched. If you want to know consistent code, you need to use a more complex regex, i.e. Pattern

and Matcher

or write your own tokenization class yourself String

.

In this example Token

, this is a class you make yourself):



public List<Token> generateTokenList(String input) {
    List<Token> = new LinkedList<>();

    for(char c : input.toCharArray()) {
        if(Character.isDigit(c)) {
           // handle digit case
        } else if (c == '+') {
           // handle plus
        } else if (c == '-') {
           // handle minus
        } else {
           /* you get the idea */
        }
    }
}

      

There are libraries out there that do this for you, like ANTLR , but this sounds like a school assignment, so you probably have to do it the hard way.

+2


source


Change the body if

to something like

if (operator.matches(function) && 
        (token[0] + token[1] + operator).length() == input.length()) 
{
    double result = 0;
    if (operator.equals("+")) {
        result = num1 + num2;
    } else if (operator.equals("-")) {
        result = num1 - num2;
    } else if (operator.equals("*")) {
        result = num1 * num2;
    } else if (operator.equals("/")) {
        result = num1 / num2;
    }
    System.out.printf("%.2f %s %.2f = %.2f%n", num1, operator, num2,
            result);
}

      



And your code works as expected.

+2


source







All Articles