java - 为什么没有显式调用时调用默认函数?
问题描述
我创建了 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
解决方案
这是因为您没有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
推荐阅读
- ios - 使用沙盒购买 Apple In App 时出现错误,因为“您的帐户已在 App Store 和 iTunes 中被禁用”
- json - 使用 powershell 5.1 基于现有文档创建 json 文档
- javascript - 如何在 ExpressJS 中插入或更新数据库
- struct - 使用 Pyspark 将大量结构字段类型转换为字符串
- java - 如何向我的 spigot 插件添加前缀/后缀命令?
- c++ - 显示窗口控件的“全尺寸”
- python - AttributeError:模块“comtypes.gen.SpeechLib”没有属性“ISpeechVoice”
- sql - 多行数据到一个表中的多列
- typescript - 将 shell 脚本与 GitHub 操作捆绑在一起的首选方式
- memory-management - 当使用 GFP_KERNEL 的参数单独调用 kmalloc 时,首选哪种类型的页面、不可移动、可回收或可移动页面?