Solved How to add a number between two numbers?

Discussion in 'Spigot Plugin Development' started by kinukin, Jan 28, 2020.

  1. So for example my highest number is 100 and my lowest number is 0 but if I add 300 for instance it will just go to the limit which is 100 and not over.

    How can I achieve this?
  2. Optic_Fusion1

    Resource Staff

    this kind of thing can easily be learned if you do java tutorials...
    • Agree Agree x 1
  3. Code (Java):
    int num1;
    int num2;
    int toAdd;
    int result = Math.max(num1, num2 + toAdd );
    • Useful Useful x 1
  4. Optic_Fusion1

    Resource Staff

    There's other methods as well however
    either way what OP wants is stupidly simple and they'd get a general idea by looking at java tutorials.
    They could of easily googled their question as well...
  5. It's going over the limit I set it to.

    I'm adding it every second in a repeating scheduler.

    Code (Text):
    int num1 = 0
    int num2 = 200
    int toAdd = 100;
    int result = Math.max(num1, num2 + toAdd );
  6. That is because I was extremely stupid and meant to do this:
    Code (Text):
    int num2 = 200
    int toAdd = 100;
    int result = Math.min(num2, num2 + toAdd );
    Agreed, but since this is such a small piece of code, why not just give it to him? I mean, this is a thing of 2 minutes for me; and I guess the problem here is the formulation. "Add a number between two numbers" is just not gonna give you a good result on any search engine. So I figured, instead of having to make him search for hours because the formulation is kind of off; I'd just give him the solution.
  7. Optic_Fusion1

    Resource Staff

    // value must be between MIN_VALUE and MAX_VALUE
    value = value > MAX_VALUE ? MAX_VALUE : value < MIN_VALUE ? MIN_VALUE : value;

    // value must be between 0 and 100
    value = value > 100 ? 100 : value < 0 ? 0 : value;

    is another way, also "java limit number to range" or similar would give the right results
    • Agree Agree x 1
  8. What about subtracting and a minimum like 0?
  9. You just got an answer ^^^ using ternary operators.
    Code (Java):
    value = value > MAX_VALUE ? MAX_VALUE : value < MIN_VALUE ? MIN_VALUE : value;

    // Could also be written as..
    if (value > MAX_VALUE) {
        value = MAX_VALUE;
    } else if (value < MIN_VALUE) {
        value = MIN_VALUE;

    // .. or even..
    value = Math.max(MIN_VALUE, Math.min(value, MAX_VALUE));
    so now you've been provided multiple ways to achieve what you desire. it's not rocket science :x
    • Agree Agree x 1