首页 > 解决方案 > 为什么没有显式调用时调用默认函数?

问题描述

我创建了 2 种方法

方法 1 - customConversion - 只有 2 个参数

方法 2 - defaultConversion - 带有 2 个参数(一个带有默认值)

我有一个场景,其中只有 method:customConversion 被代码显式调用,但我在输出中发现 method:defaultConversion 也被调用

我无法得出关于 method:defaultConversion 是如何被调用的结论?

class Conversion{

    public def customConversion(int price, int rate){
        println "customConversion -> Price ->"+price+"Rate ->"+rate;
        double result = (rate*price);
        println "The amount is "+result;
    }

    public def defaultConversion(int price,int rate=60){
        println "defaultConversion -> Price ->"+price+"Rate ->"+rate;
        double result = (rate*price);
        println "The amount is "+result;
    }

    public static void main(String[] args){

        Scanner scan = new Scanner(System.in);
        double result = 0;

        Conversion c = new Conversion();

        println "Enter the price:";
        int price = Integer.parseInt(scan.nextLine());

        println "1.Custom Conversion\n2.Default Conversion\nEnter the choice:"
        int choice = Integer.parseInt(scan.nextLine());

        switch(choice){
            case 1:
            println "Enter the conversion rate:";
            int rate = Integer.parseInt(scan.nextLine());
            c.customConversion(price,rate);

            case 2:
            c.defaultConversion(price);
        }//End of switch

    }//End of main
}//End of class

输入:200 1 45

Actual Output:
Enter the price:
1.Custom Conversion
2.Default Conversion
Enter the choice:
Enter the conversion rate:
customConversion -> Price ->200Rate ->45
The amount is 9000.0
defaultConversion -> Price ->200Rate ->60
The amount is 12000.0

Expected Output:
Enter the price:
1.Custom Conversion
2.Default Conversion
Enter the choice:
Enter the conversion rate:
customConversion -> Price ->200Rate ->45
The amount is 9000.0

标签: javagroovy

解决方案


这是因为您没有break在 case 末尾写 a ,请尝试break;在每个 case 之后添加:

switch(choice){
            case 1:
            println "Enter the conversion rate:";
            int rate = Integer.parseInt(scan.nextLine());
            c.customConversion(price,rate);
            break; 

            case 2:
            c.defaultConversion(price);
            break; 
        }//End of switch

这是w3schools 链接,它在一小段中解释了为什么要在语句中添加break关键字。switch


推荐阅读