Returning different messages according to the results of a function

Asked

Viewed 63 times

1

I have the following doubt:

I have a function that can give me four different values. I would like to create a message (string) for each function value, so that the message is released with its respective value, for example:

If the function returns B, I have message B, if the function returns value A, I have message A...

code:

 Double N1 = N1(b, a, A, B, C, D);

 String resultado = (N1 == A && N1 < nM ? "Tipo A" : (N1 == B && N1 < nM ? "Tipo B": (N1 == C && N1 < nM ? "Tipo C" : (N1 == D && N1 < nM ? "Tipo D" : "Passa!"))));

The function value is N1, which can be if A, B, C or D. In addition, the "Type X" message should only appear if N1 is less than double nM. If nM is less than N1, I must return the message "Passes!"

The problem is the message I get is always "Pass!" even when nM is greater than N1.

How should I proceed?

1 answer

1

Try to do something like this:

Map<Double, String> mensagens = new HashMap<>(4);
mensagens.put(A, "Tipo A");
mensagens.put(B, "Tipo B");
mensagens.put(C, "Tipo C");
mensagens.put(D, "Tipo D");

Double escolhido = N1(b, a, A, B, C, D);
String resultado = nM > escolhido ? "Passa" : mensagens.get(escolhido);

However, you did not provide much information about the context of this code. I believe that with more information about the context of the problem, a better solution should exist. In particular, if you give more information about what they are, what they do and what the variables are for N1, nM, a, b, A, B, C and D, types A, B, C and D and "Pass". I recommend that you read about the XY problem.

Also, make sure that there is no error within the method N1.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.