如何避免使用过多的&&和||

时间:2016-11-17 01:57:56

标签: java

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"); } 

是否有更简单的方法来判断允许哪种货币,哪种货币不允许? (参见不支持)。

有人告诉我这么多&amp;&amp;或||对代码不好。这是对的吗?

1 个答案:

答案 0 :(得分:3)

一般情况下,许多||&&编码错误并非如此。但多余的并不好。在您的情况下,因为您只支持两种类型的转换,所以可以简化操作:

    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
    }  

之前您检查过两次不受支持的转化:在第一个 if 中,还隐含在最后一个 else 中。另外我应该指出,在这两种情况下你都进行相同的转换,所以可能存在错误。