Mr.Rendero Mr.Rendero - 18 days ago 4
Java Question

How to avoid using too many && and ||

package CurrencyConverter;

import java.util.Scanner;

public class CurrencyConverter {

public static void main(String[] args) {

System.out.println("Welcome to the Currency Converter"
+ " \"MONEY MONEY KACHINGG\"\n ");

Scanner s = new Scanner(System.in);
System.out.print("Enter desired amount: ");
double amount = s.nextDouble();
//----------------Supported Amount------------------------------------------
if(amount < 0 || amount > 1000) {
System.out.println("Amount must be between 0 and 1000");
return; }
//--------------------------------------------------------------------------
System.out.print("Type currency to START FROM: ");
String from = s.next();
System.out.print("Type currency to CONVERT TO: ");
String to = s.next();

double currency;
//-----------------------UNSUPPORTED------------- ---------------------------
if((!from.equals("BGN") && !to.equals("USD")) &&
(!from.equals("USD") && !to.equals("BGN"))) {

System.out.println("Unsupported Currency!\n"
+ "Please choose from BGN or USD"); }
//------------------------BGN to USD----------------------------------------
else if(from.equals("BGN") && to.equals("USD")) {
for(currency = 0; currency <= amount; currency++) {
System.out.printf("%.2f leva = %.2f $\n",currency,(currency/1.52)); }
}
//------------------------USD to BGN----------------------------------------
else if(from.equals("USD") && to.equals("BGN")) {
for(currency = 0; currency <= amount; currency++) {
System.out.printf("%.2f $ = %.2f leva\n",currency,(currency/1.52)); }
}
//------------------------Incorrect-----------------------------------------
else {
System.out.println("Unsupported Currency!\n"
+ "Please choose from BGN or USD"); }


Is there an easier way to tell which currency is allowed and which is not? (See UNSUPPORTED).

I was told that so many && or || are not good for the code. Is that correct?

Answer

In general, it's not true that many || or && is bad coding. Having excess is not good though. In your case since you only support two types of conversion you can simplify things:

    if(from.equals("BGN") && to.equals("USD")) {
       for(currency = 0; currency <= amount; currency++) {
           System.out.printf("%.2f leva = %.2f $\n",currency,(currency/1.52)); }
    }
    else if(from.equals("USD") && to.equals("BGN")) {
        for(currency = 0; currency <= amount; currency++) {
            System.out.printf("%.2f $ = %.2f leva\n",currency,(currency/1.52)); }
    }
    else {
    //unsupported
    }  

Previously you were checking for unsupported conversions twice: in the first if, and also implicitly in the last else. Also I should point out that you are doing the same conversion in both cases, so something is likely wrong there.

Comments