سؤال

I am 99% sure that this cannot be done, however I thought I would ask to be certain.

I am attempting to create an application that calculates the required dice roll for an action in a popular tabletop war game.

The following is this calculation in Java

        int x = ((WSattacker * 2) - WSdefender);
        int y = (WSattacker - WSdefender);

        String result;

        // Calculation for a +5
        if (x <= -1) {

            result = "5+";
        }

        // Calculation for a +4
        else if (x >= 0 && y <= 0) {

            result = "4+";
        }

        // Calculation for a +3
        else if (y > 0) {

            result = "3+";
        } else {

            result = "Error";
        }

        return result;

Now my issue is that to avoid copywriter infringement I cannot mention the name of the game in my application, and probably cannot hard code the above calculation in the app.

This means that it is difficult to tell a potential user what the app will do.

The only solution I can think of is to make the application generic and allow the user to input the calculation required in the form of an equation.

An equation that I can place anonymously on a public board or similar.

Therefore my questions are as follows.

  1. Is there another way of going about this?
  2. If no, is it possible to condense the above code into a single expression/ equationi.e. one that removes the if and else statements
هل كانت مفيدة؟

المحلول

To answer question 2:

result = test_condition_1 ? result2_if_true : (test_condition_2 ? result2_if_true : test3_or_result2);

You can then build up 'compound' test conditions this way, and it's based upon ternary operators.

EDIT

Ternary operators are a short-hand way of writing if..then..else statments, and more information can be found in the wiki-link above. An example of its use is below, which you can compile and run:

public class TernaryTest {

    public static void main(String [] args){
    int x = 14;
    int y = 5;
        String result = ( x <= 10 ) ? "Less than 10" : "More than 10";
        System.out.println("Result is: " + result);
    }
}

Try running it and see the result as you change the value of x to understand how it works. Then it's possible to extend it to include and else by replacing the "more than 10" string.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top