2

I have been wondering how and/or if you can use a char for equations. And please don't comment "why wud u want to do that"?

Example:

public static void main(String... args) {

    char equalitySign = '<';

    boolean check = 5 equalitySign 10;

} 

I know the above code won't run(obvisously), but I was wondering if there was a similar way of doing so. Or would I just have to use if/switch statements?

Example 2:

public static void main(String... args) {

    char equalitySign = '<';
    boolean check;

    if (equalitySign == '<' + '=') {
        check = 5 <= 10; 
        System.out.println("is 5 less than or equal to 10, " + check);
    } else if (equalitySign == '<') {
        check = 5 < 10; 
        System.out.println("5 is less than 10, " + check);
    } else if (equalitySign == '>') {
        check = 5 > 10; 
        System.out.println("5 is greater than 10, " + check);
    }

}

Thanks!

StarCoder
  • 251
  • 1
  • 3
  • 16
  • 1
    Not directly, but you can build a `String` out of your operands and character operator and then [evaluate it as a mathematical expression](https://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form). I wouldn't really recommend it, but `System.out.println(new ScriptEngineManager().getEngineByName("JavaScript").eval("5 < 10")); // true` – azurefrog Oct 26 '17 at 21:44
  • @azurefrog Okay, thanks! I check that out. – StarCoder Oct 26 '17 at 21:48
  • This `'<' + '='` is numeric addition and will result in `equalitySign` being compared to the character `y`. It's not string concatenation, and even if it was you wouldn't be able to compare a `String` and a `char`. – Sotirios Delimanolis Oct 26 '17 at 21:49
  • @SotiriosDelimanolis Oh okay, thanks for the info. – StarCoder Oct 26 '17 at 21:51

4 Answers4

3

"Example 2" is the way to go for you. Just use if-else if instead of all if statements or switch-case statements.

Note - as pointed out by one of the commenters, you might want to use String comparison since one of your operators is "<=" which is more than 1 character. So you will have to stick to using if-else if instead of switch case.

VHS
  • 9,534
  • 3
  • 19
  • 43
2

As others have noted, a Map of possible comparisons would work as well. First, we need an interface to declare a comparison method:

interface IntComparator { boolean compare(int left, int right); }

Then a map of possible comparisons:

Map<String, IntComparator> comparisons = new HashMap<>();
comparisons.put("=", (l, r) -> { return l == r; });
comparisons.put("<", (l, r) -> { return l < r; });

now you can just use the comparison you're interested in by looking up the correct Comparator in your map:

System.out.println(comparisons.get("=").compare(1, 2));
System.out.println(comparisons.get("<").compare(1, 2));

Example in ideone.com


Note: My best days in Java are long over, in C# where primitives are allowed in generics and we have a delegate type, this could be a lot cleaner. I am not sure whether my code is considered good code these days.

tkausl
  • 13,686
  • 2
  • 33
  • 50
0

Using a Map

You could have a map from string operand to bifunction from number and number to boolean.

You could then get the bifunction, with a default function that throws an exception, using the given operand as the key.

You can then invoke the function on the arguments and return the result.

Example code

Java 9, but can be Java 8 if the Map creation is changed to not use Map.of

import java.util.Map;
import java.util.function.BiFunction;

public class Example {
    @FunctionalInterface
    interface Operation extends BiFunction<Integer, Integer, Boolean>{}

    public static final Map<String, Operation> HANDLERS = Map.of(
        ">", (p,q) -> p > q,
        "<", (p,q) -> p < q,
        "<=", (p,q) -> p <= q
    );

    public static boolean evaluate(int first, String operator, int second) {
        final Operation handler = HANDLERS.getOrDefault(operator, (p,q) -> {
                throw new AssertionError("Bad operator: " + operator);
        });
        return handler.apply(first, second);
    }

    public static void main(final String... args) {
        System.out.println(evaluate(1, "<", 3));
        System.out.println(evaluate(3, "<", 1));
        System.out.println(evaluate(1, "<=", 3));
        System.out.println(evaluate(3, "<=", 3));
        System.out.println(evaluate(3, "%", 3));
    }
}
jrtapsell
  • 6,719
  • 1
  • 26
  • 49
  • 1
    Yeah, Maps are one of the basic data structures which you will need to use. Using HashMaps for caching for example can really speed up code. – jrtapsell Oct 26 '17 at 22:01
  • No problem, the bifunction bit is part of the new functional features added in Java 8 (bifunction converts 2 values to 1 value, like > which turns 2 numbers into a boolean). – jrtapsell Oct 26 '17 at 22:04
-3

In fact:

char c1 = 'a';
char c2 = 'b';
System.out.println(c1 < c2); // This is print true

This is because each char value has a corresponding ASCII value. ASCII values are ints, which are comparable by definition.

ASCII table found here: https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html

Teju
  • 47
  • 1
  • 7