Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java geting operators from within a split for function purpose

Okay... I think I might have gone over my head with trying to simplify this code. I place operators such as ( *, +, /, -) in a split. Know i want to call them individually to do their perspective task in a if (operators.equals.(+)){ return num1 + num2. } then for *, -, / perspectively

how can i do that correctly having using math in my earlier 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");
}
like image 577
Integral Avatar asked Jun 21 '26 23:06

Integral


2 Answers

You don't.

String.split only returns the parts of the String that were not matched. If you want to know the matched code, you need to use a more sophisticated regular expression, i.e. the Pattern and Matcher classes, or write your own String tokenization class yourself.

In this example Token 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 that do this for you, such as ANTLR but this sounds like a school assignment so you probably have to do this the hard way.

like image 168
durron597 Avatar answered Jun 24 '26 12:06

durron597


Change your if body 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.

like image 40
Elliott Frisch Avatar answered Jun 24 '26 11:06

Elliott Frisch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!