if (currencyChosen.equals("RANDOM3") & convertTo.equals("RANDOM3"))
JOptionPane.showMessageDialog(null, "SAME SENTENCE");
else if (currencyChosen.equals("RANDOM2") & convertTo.equals("RANDOM2"))
JOptionPane.showMessageDialog(null, "SAME SENTENCE");
else if (currencyChosen.equals("RANDOM") & convertTo.equals("RANDOM"))
JOptionPane.showMessageDialog(null, "SAME SENTENCE");
If I had a code like this with multiple, but similar if statements with different if criteria, is there a way to make it more short and neat?
It sounds like you probably want something like:
private static final List<String> VALID_CURRENCIES =
Arrays.asList("RANDOM", "RANDOM2", "RANDOM3");
...
if (currencyChosen.equals(convertTo) && VALID_CURRENCIES.contains(currencyChosen)) {
JOptionPane.showMessageDialog(null, "SAME SENTENCE");
}
Adjust the variable names to suit your context. You could also use a Set<String>
instead of a List<String>
if the order is never important... with a small number of valid options it won't make much difference in performance though. The O(1) nature of a HashSet
vs O(N) of a list only matters when N becomes large. Of course, you may want to use Set<String>
anyway, to make the intention of treating it only as a set clearer. My guess is that you may well have another reason to have a list of the valid currencies (in a particular order) anyway though - in which case, use that list here as well.
However, with your description of the context:
I'm having to write a basic converter and I was trying to output that, for example, choosing "Convert from US dollars to US dollars" would output "You can't perform that action
it sounds like you probably only need
if (currencyChosen.equals(convertTo)) {
...
}
If you're somehow allowing currencyChosen
and convertTo
to not be valid, you should check for that first:
if (!VALID_CURRENCIES.contains(currencyChosen)) {
// Display error for invalid source currency
return;
}
if (!VALID_CURRENCIES.contains(convertTo)) {
// Display error for invalid target currency
return;
}
if (currencyChosen.equals(convertTo)) {
// Display error for source == target
return;
}
Basically, try to make your error conditions orthogonal as far as you can.
See more on this question at Stackoverflow